wps集成代码应用提交

This commit is contained in:
yujh 2024-07-16 10:16:56 +08:00
parent f7245555df
commit 83ad5a256c
12 changed files with 1706 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package com.awspaas.user.apps.yiliwps.constant;
import com.actionsoft.sdk.local.SDK;
public class YiliWpsConst {
public static final String APPID = "com.awspaas.user.apps.yiliwps";
public static final String FILE_APPID = "com.actionsoft.apps.coe.pal";
public static final String COE_UPFILE = "COE_Upfile";
public static final String HOST = SDK.getAppAPI().getProperty(APPID,"host_config");
public static final String CONTENT_TYPE = "application/json";
public static final String AK = SDK.getAppAPI().getProperty(APPID,"AK");
public static final String SK = SDK.getAppAPI().getProperty(APPID,"SK");
public static final String WPS_FILETYPE_W="w";
public static final String WPS_FILETYPE_S="s";
public static final String WPS_FILETYPE_P="p";
public static final String WPS_FILETYPE_F="f";
public static final String SUPPORTTYPE_W = "doc, dot, wps, wpt, docx, dotx, docm, dotm";
public static final String SUPPORTTYPE_S = "xls, xlt, et, xlsx, xltx, csv, xlsm, xltm";
public static final String SUPPORTTYPE_P = "ppt,pptx,pptm,ppsx,ppsm,pps,potx,potm,dpt,dps";
public static final String SUPPORTTYPE_F = "pdf";
//bo相关
public static final String BO_EU_SYSTEM_DEMO_FILE = "BO_EU_SYSTEM_DEMO_FILE";
public static final String APP_ACT_COE_PAL_UPFILE = "APP_ACT_COE_PAL_UPFILE";
}

View File

@ -0,0 +1,33 @@
package com.awspaas.user.apps.yiliwps.controller;
import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryModel;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.awspaas.user.apps.yiliwps.web.WpsWeb;
import java.util.List;
@Controller
public class YiliWpsController {
public final static LogAPI logAPI = SDK.getLogAPI();
@Mapping("com.awspaas.user.apps.yiliwps.previewUrl")
public String getWPSOnlineFilePreviewUrl(UserContext me,String palId,String fileName) throws Exception{
WpsWeb web =new WpsWeb(me);
return web.getWPSOnlineFilePreviewUrl(palId,fileName);
}
/**
* 获取新的pal模型文件
* @param me
* @param palId
* @return
*/
@Mapping("com.awspaas.user.apps.yiliwps.getCoeDefinition")
public String getCoeDefinition(UserContext me,String palId){
WpsWeb web =new WpsWeb(me);
return web.getCoeDefinition(palId);
}
}

View File

@ -0,0 +1,131 @@
package com.awspaas.user.apps.yiliwps.restful;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.HandlerType;
import com.actionsoft.bpms.server.conf.portal.AWSPortalConf;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.ORGAPI;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.yiliwps.web.WpsWeb;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import javax.ws.rs.*;
import java.io.File;
@Controller(type = HandlerType.RESTFUL, apiName = "WPSapi", desc = "WPS集成API")
public class YiliWpsApi {
public LogAPI logApi = SDK.getLogAPI();
@Path("/v1/3rd/file/info")
@GET
public String fileInfo(@HeaderParam("X-Weboffice-File-Id") String headFileId,
@QueryParam("_w_third_palId") String palId,
@QueryParam("_w_third_queryFileId") String queryFileId,
@QueryParam("_w_third_sid") String sid,
@QueryParam("_w_third_fname") String fileName
) {
JSONObject params = new JSONObject();
UserContext _uc = UserContext.fromSessionId(sid);
logApi.consoleInfo(">>>>>文件信息请求成功/v1/3rd/file/info"+palId+","+headFileId+queryFileId+sid+fileName);
WpsWeb web =new WpsWeb(_uc);
return web.getFileInfo(sid,palId,queryFileId,fileName);
}
@Path("/v1/3rd/user/info")
@POST
public String userInfo(@RequestBody String ids2,
@QueryParam("_w_third_sid") String sid) {
logApi.consoleInfo(">>>>>用户信息请求成功/v1/3rd/user/info"+sid);
JSONObject jsonObject = JSONObject.parseObject(ids2);
JSONArray array = jsonObject.getJSONArray("ids");
UserContext userContext = UserContext.fromSessionId(sid);
JSONArray resultArray = new JSONArray();
JSONObject resultJson = new JSONObject();
ORGAPI orgapi = SDK.getORGAPI();
for (int i = 0; i < array.size(); i++) {
String userId = array.getString(i);
UserModel user = orgapi.getUser(userId);
JSONObject userModel = new JSONObject();
userModel.put("id",userId);
userModel.put("name",user.getUserName());
String userPhoto = SDK.getPortalAPI().getUserPhoto(userContext, userId);
String avatar_url = AWSPortalConf.getUrl() +"/r" + userPhoto.substring(1,userPhoto.length());
userModel.put("avatar_url",avatar_url);
resultArray.add(userModel);
}
resultJson.put("users",resultArray);
System.out.println("resultJson.toString() = " + resultJson.toString());
return resultJson.toString();
}
@Path("/v1/3rd/file/save")
@POST
public String save(@Multipart("file") File file,
@HeaderParam("x-weboffice-save-type") String save_type,
@QueryParam("_w_third_queryFileId") String queryFileId,
@QueryParam("_w_third_palId") String palId,
@QueryParam("_w_third_sid") String sid,
@QueryParam("_w_third_fname") String fileName) {
JSONObject params = new JSONObject();
System.out.println("file.getName() = " + file.getName());
System.out.println("file.size() = " + file.length());
System.out.println("queryFileId = " + queryFileId);
System.out.println("palId = " + palId);
System.out.println("sid = " + sid);
System.out.println("fileName = " + fileName);
System.out.println(">>>>>>文件保存调用成功:"+System.currentTimeMillis());
WpsWeb web = new WpsWeb();
String fileInfo = web.saveFileInfo(save_type,palId,queryFileId,sid,fileName,file);
return fileInfo;
}
@Path("/v1/3rd/file/history")
@POST
public String histoty(@QueryParam("_w_boId") String boId,
@QueryParam("_w_boItemName") String boItemName,
@QueryParam("_w_sid") String sid){
System.out.println(">>>>>>文件历史调用成功:"+System.currentTimeMillis());
JSONObject params = new JSONObject();
params.put("boItemName", boItemName);
params.put("boId", boId);
params.put("sid", sid);
WpsWeb web = new WpsWeb();
return web.getHistoryFileInfo(params);
}
@Path("/v1/3rd/file/version/{version}")
@GET
public String fileVersionInfo(@PathParam("version") int version,
@QueryParam("_w_boId") String boId,
@QueryParam("_w_boItemName") String boItemName,
@QueryParam("_w_sid") String sid){
JSONObject params = new JSONObject();
System.out.println(">>>>>>文件版本调用成功:"+System.currentTimeMillis());
params.put("boItemName", boItemName);
params.put("boId", boId);
params.put("sid", sid);
params.put("version", version);
WpsWeb web = new WpsWeb();
return web.getVersionFileInfo(params);
}
@Path("/test")
@GET
public String sayHelloQueryParam(@QueryParam("name") String name) {
return "hello,world!-QueryParam " + name;
}
@Path("/test/{name}")
@POST
public String sayHelloparam(@PathParam("name") String name) {
return "test,hello,world!-param " + name;
}
}

View File

@ -0,0 +1,224 @@
package com.awspaas.user.apps.yiliwps.tools;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.MD5;
import com.actionsoft.bpms.util.UtilString;
import com.awspaas.user.apps.yiliwps.constant.YiliWpsConst;
import com.awspaas.user.apps.yiliwps.utils.WPSOnlineUtil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static com.actionsoft.bpms.util.Base64.encodeBase64String;
public class WPSOnlineTool {
/**
* 移动端单参数
* @param sourceDc
* @return
*/
public static String getFilePreviewUrl(DCContext sourceDc) {
String appId = sourceDc.getAppId();
String repositoryName = sourceDc.getRepositoryName();
String groupValue = sourceDc.getGroupValue();
String fileValue = sourceDc.getFileValue();
String fileName = sourceDc.getFileName();
String filePath = sourceDc.getFilePath();
String watermark = "";
String watermarkFont = "";
String watermarkFontColor = "";
if (sourceDc.getExtParams().containsKey("watermark")) {
watermark = (String) sourceDc.getExtParams().get("watermark");
}
if (sourceDc.getExtParams().containsKey("watermarkFont")) {
watermarkFont = (String) sourceDc.getExtParams().get("watermarkFont");
}
if (sourceDc.getExtParams().containsKey("watermarkFontColor")) {
watermarkFontColor = (String) sourceDc.getExtParams().get("watermarkFontColor");
}
long lastModifyFile = sourceDc.getFileLastModified();//1492684940463
String fileId =getFileId(filePath,lastModifyFile);//31e42c7824b9466d32ed088d4c37dbb5
String fileType = WPSOnlineUtil.getFileType(fileName);
//https://wwo.wps.cn/office/<:type>/<:fileid>?_w_appid=xxxxxxxxxx&_w_signature=xxxxxxxxxxx&(对接模块需要的自定义参数)
StringBuilder url = new StringBuilder();
url.append(YiliWpsConst.HOST);
url.append(fileType);
url.append("/");
url.append(fileId);
url.append("?");
String wpsurl = url.toString();
try {
Map paramMap= new HashMap<String, String>();
paramMap.put("_w_appid", YiliWpsConst.APPID);
paramMap.put("_w_fname", URLEncoder.encode(fileName, "UTF-8"));
paramMap.put("_w_sourceappid",appId);
paramMap.put("_w_repository",repositoryName);
paramMap.put("_w_gvalue", groupValue);
paramMap.put("_w_fvalue",fileValue);
paramMap.put("_w_sid",sourceDc.getSession().getSessionId());
paramMap.put("_w_wmark",watermark);
paramMap.put("_w_wmarkfont",watermarkFont);
paramMap.put("_w_wmarkcolor",watermarkFontColor);
String signature = getSignature(paramMap, YiliWpsConst.SK);
wpsurl += getUrlParam(paramMap) + "&_w_signature=" + signature;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//System.out.println("WPSOnlineUrl---->>>"+wpsurl);
return wpsurl;
}
/**
* pc扩展参数
* @param sourceDc
* @param boId
* @param taskInstId
* @param processInstId
* @param boDefId
* @param boItemName
* @return
*/
public static String getFilePreviewUrl(DCContext sourceDc,String boId,String taskInstId,String processInstId,String boDefId,String boItemName) {
String appId = sourceDc.getAppId();
String repositoryName = sourceDc.getRepositoryName();
if(UtilString.isEmpty(repositoryName)){
repositoryName = "!from-ui-file-";
}
String groupValue = sourceDc.getGroupValue();
String fileValue = sourceDc.getFileValue();
String fileName = sourceDc.getFileName();
String filePath = sourceDc.getFilePath();
String watermark = "";
String watermarkFont = "";
String watermarkFontColor = "";
if (sourceDc.getExtParams().containsKey("watermark")) {
watermark = (String) sourceDc.getExtParams().get("watermark");
}
if (sourceDc.getExtParams().containsKey("watermarkFont")) {
watermarkFont = (String) sourceDc.getExtParams().get("watermarkFont");
}
if (sourceDc.getExtParams().containsKey("watermarkFontColor")) {
watermarkFontColor = (String) sourceDc.getExtParams().get("watermarkFontColor");
}
long lastModifyFile = sourceDc.getFileLastModified();//1492684940463
String fileId =getFileId(filePath,lastModifyFile);//31e42c7824b9466d32ed088d4c37dbb5
String fileType = WPSOnlineUtil.getFileType(fileName);
//https://wwo.wps.cn/office/<:type>/<:fileid>?_w_appid=xxxxxxxxxx&_w_signature=xxxxxxxxxxx&(对接模块需要的自定义参数)
StringBuilder url = new StringBuilder();
url.append(YiliWpsConst.HOST);
url.append(fileType);
url.append("/");
url.append(fileId);
url.append("?");
String wpsurl = url.toString();
try {
Map paramMap= new HashMap<String, String>();
paramMap.put("_w_appid", YiliWpsConst.APPID);
paramMap.put("_w_fname", URLEncoder.encode(fileName, "UTF-8"));
paramMap.put("_w_sourceappid",appId);
paramMap.put("_w_repository",repositoryName);
paramMap.put("_w_gvalue", groupValue);
paramMap.put("_w_fvalue",fileValue);
paramMap.put("_w_sid",sourceDc.getSession().getSessionId());
paramMap.put("_w_wmark",watermark);
paramMap.put("_w_wmarkfont",watermarkFont);
paramMap.put("_w_wmarkcolor",watermarkFontColor);
paramMap.put("_w_boId",boId);
paramMap.put("_w_taskInstId",taskInstId);
paramMap.put("_w_processInstId",processInstId);
paramMap.put("_w_boDefId",boDefId);
paramMap.put("_w_boItemName",boItemName);
String signature = getSignature(paramMap, YiliWpsConst.SK);
wpsurl += getUrlParam(paramMap) + "&_w_signature=" + signature;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//System.out.println("WPSOnlineUrl---->>>"+wpsurl);
return wpsurl;
}
public static String getFileId(String filePath,long lastModifyFile){
MD5 md5 = new MD5();
return md5.toDigest(filePath+lastModifyFile,"UTF-8");
}
private static String getUrlParam(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (builder.length() > 0) {
builder.append('&');
}
builder.append(URLEncoder.encode(entry.getKey(), "utf-8")).append('=').append(URLEncoder.encode(entry.getValue(), "utf-8"));
}
return builder.toString();
}
private static String getSignature(Map<String, String> params, String appSecret) {
List<String> keys=new ArrayList();
for (Map.Entry<String, String> entry : params.entrySet()) {
keys.add(entry.getKey());
}
// 将所有参数按key的升序排序
Collections.sort(keys, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
// 构造签名的源字符串
StringBuilder contents=new StringBuilder("");
for (String key : keys) {
if (key=="_w_signature"){
continue;
}
contents.append(key+"=").append(params.get(key));
//System.out.println("key:"+key+",value:"+params.get(key));
}
contents.append("_w_secretkey=").append(appSecret);
try {
// 进行hmac sha1 签名
byte[] bytes= hmacSha1(appSecret.getBytes("UTF-8"),contents.toString().getBytes("UTF-8"));
//字符串经过Base64编码
String sign= encodeBase64String(bytes);
sign = URLEncoder.encode( sign, "UTF-8");
return sign;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//System.out.println(sign);
return "";
}
public static byte[] hmacSha1(byte[] key, byte[] data) {
try {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance(signingKey.getAlgorithm());
mac.init(signingKey);
return mac.doFinal(data);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String path = "http://192.168.0.211:7020"+"/r";
String s = "./df?groupValue=taskfile&fileValue=admin&sid=90647d37-f19c-43e9-a1ad-5bf31879f134&repositoryName=-task-&appId=com.actionsoft.apps.taskmgt&attachment=true&fileNameShow=%E4%B8%93%E9%A1%B9%E9%99%84%E5%8A%A0%E6%89%A3%E9%99%A4%E4%BF%A1%E6%81%AF.xls&fileName=%E4%B8%93%E9%A1%B9%E9%99%84%E5%8A%A0%E6%89%A3%E9%99%A4%E4%BF%A1%E6%81%AF_152615bf-1be3-4a95-9cfb-75dc35d89a5f.xls&lastModified=1546831657000";
s = s.substring(1,s.length());
System.out.println(path+s);
}
}

View File

@ -0,0 +1,167 @@
package com.awspaas.user.apps.yiliwps.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AvatarUtil {
/**
* 绘制字体头像
* 如果是英文名只显示首字母大写
* 如果是中文名只显示最后两个字
* @param name
* @throws IOException
*/
public static void generateImg(String name,OutputStream outputStream)
throws IOException {
int width = 120;
int height = 120;
int nameLen = name.length();
String nameWritten;
//如果用户输入的姓名少于等于2个字符不用截取
if (nameLen <= 2) {
nameWritten = name;
} else {
//如果用户输入的姓名大于等于3个字符截取后面两位
String first = name.substring(0, 1);
if (isChinese(first)) {
//截取倒数两位汉字
nameWritten = name.substring(nameLen - 2);
} else {
//截取前面的两个英文字母
nameWritten = name.substring(0, 2).toUpperCase();
}
}
// Font font = new Font("Droid Sans", Font.PLAIN, 30);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 这里可以使用随机颜色值或者自定义颜色值, 比如常用的蓝色值 new Color(0xff3296fa)
g2.setBackground(getRandomColor());
g2.clearRect(0, 0, width, height);
g2.setPaint(Color.WHITE);
Font font = null;
//两个字及以上
if(nameWritten.length() >= 2) {
font = new Font("Droid Sans", Font.PLAIN, 40);
g2.setFont(font);
String firstWritten = nameWritten.substring(0, 1);
String secondWritten = nameWritten.substring(1, 2);
//两个中文 言曌
if (isChinese(firstWritten) && isChinese(secondWritten)) {
g2.drawString(nameWritten, 20, 70);
}
//首中次英 罗Q
else if (isChinese(firstWritten) && !isChinese(secondWritten)) {
g2.drawString(nameWritten, 27, 70);
//首英, AB
} else {
nameWritten = nameWritten.substring(0,1);
}
}
//一个字
if(nameWritten.length() ==1) {
//中文
if(isChinese(nameWritten)) {
font = new Font("Droid Sans", Font.PLAIN, 70);
g2.setFont(font);
g2.drawString(nameWritten, 25, 70);
}
//英文
else {
font = new Font("Droid Sans", Font.PLAIN, 80);
g2.setFont(font);
g2.drawString(nameWritten.toUpperCase(), 33, 80);
}
}
BufferedImage rounded = makeRoundedCorner(bi, 0);
ImageIO.write(rounded, "png", outputStream);
}
/**
* 判断字符串是否为中文
* @param str
* @return
*/
public static boolean isChinese(String str) {
String regEx = "[\\u4e00-\\u9fa5]+";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
if (m.find())
return true;
else
return false;
}
/**
* 获得随机颜色
* @return
*/
private static Color getRandomColor() {
String[] beautifulColors =
new String[]{"232,221,203", "205,179,128", "3,101,100", "3,54,73", "3,22,52",
"237,222,139", "251,178,23", "96,143,159", "1,77,103", "254,67,101", "252,157,154",
"249,205,173", "200,200,169", "131,175,155", "229,187,129", "161,23,21", "34,8,7",
"118,77,57", "17,63,61", "60,79,57", "95,92,51", "179,214,110", "248,147,29",
"227,160,93", "178,190,126", "114,111,238", "56,13,49", "89,61,67", "250,218,141",
"3,38,58", "179,168,150", "222,125,44", "20,68,106", "130,57,53", "137,190,178",
"201,186,131", "222,211,140", "222,156,83", "23,44,60", "39,72,98", "153,80,84",
"217,104,49", "230,179,61", "174,221,129", "107,194,53", "6,128,67", "38,157,128",
"178,200,187", "69,137,148", "117,121,71", "114,83,52", "87,105,60", "82,75,46",
"171,92,37", "100,107,48", "98,65,24", "54,37,17", "137,157,192", "250,227,113",
"29,131,8", "220,87,18", "29,191,151", "35,235,185", "213,26,33", "160,191,124",
"101,147,74", "64,116,52", "255,150,128", "255,94,72", "38,188,213", "167,220,224",
"1,165,175", "179,214,110", "248,147,29", "230,155,3", "209,73,78", "62,188,202",
"224,160,158", "161,47,47", "0,90,171", "107,194,53", "174,221,129", "6,128,67",
"38,157,128", "201,138,131", "220,162,151", "137,157,192", "175,215,237", "92,167,186",
"255,66,93", "147,224,255", "247,68,97", "185,227,217"};
int len = beautifulColors.length;
Random random = new Random();
String[] color = beautifulColors[random.nextInt(len)].split(",");
return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]),
Integer.parseInt(color[2]));
}
/**
* 图片做圆角处理
* @param image
* @param cornerRadius
* @return
*/
public static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
int w = image.getWidth();
int h = image.getHeight();
BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = output.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(image, 0, 0, null);
g2.dispose();
return output;
}
}

View File

@ -0,0 +1,48 @@
package com.awspaas.user.apps.yiliwps.utils;
import com.actionsoft.apps.coe.pal.pal.repository.cache.PALRepositoryCache;
import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryModel;
import com.actionsoft.apps.resource.plugin.profile.DCPluginProfile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.AppAPI;
import com.awspaas.user.apps.yiliwps.constant.YiliWpsConst;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class CallASLPUtil {
/**
* 调用重新生成文档
* @return
*/
public String callTranslateDocASLP(UserContext me, String groupValue, String fileName, FileInputStream fileInputStream){
Map<String, Object> params = new HashMap<>();
DCPluginProfile dcProfilepdf = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal.datamigration",
"migration");
DCContext dcContextpdf = new DCContext(me, dcProfilepdf, "com.actionsoft.apps.coe.pal.datamigration",
"policyFile", groupValue, fileName);
System.out.println(">>>>>>>>>>>>开始写入 ");
boolean write = SDK.getDCAPI().write(fileInputStream, dcContextpdf);
System.out.println(">>>>>>>>>>>>结束写入 "+write);
params.put("sid",me.getSessionId());
params.put("groupValue","policyFile");
params.put("ruuid",groupValue);
params.put("fileNames",fileName);
String sourceAppId = YiliWpsConst.APPID;
// aslp服务地址
String aslp = "aslp://com.actionsoft.apps.coe.pal.datamigration/TranslateDoc";
// 参数定义列表
AppAPI appAPI = SDK.getAppAPI();
//开发者注册报告生成器扩展App
ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
System.out.println("ro = " + ro);
return ro.toString();
}
}

View File

@ -0,0 +1,23 @@
package com.awspaas.user.apps.yiliwps.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateUtil {
public static Long getCurrentSeconds(){
Date date = new Date();
String timestamp = String.valueOf(date.getTime()/1000);
return Long.valueOf(timestamp);
}
public static String getDateNow() {
SimpleDateFormat sdf4 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf4.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf4.format(new Date());
}
}

View File

@ -0,0 +1,267 @@
package com.awspaas.user.apps.yiliwps.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncryptionUtil {
/**
* 加密算法
*/
private static final String ENCRY_ALGORITHM = "AES";
/**
* 加密算法/加密模式/填充类型
* 本例采用AES加密ECB加密模式PKCS5Padding填充
*/
private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
return null;
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256HMAC.init(secret_key);
byte[] array = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) |
0x100).substring(1, 3));
}
return sb.toString();
}
/**
* 利用java原生的摘要实现SHA256加密
*
* @param str 加密后的报文
* @return
*/
public static String getSHA256StrJava(byte[] str) {
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str);
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encodeStr;
}
/**
*
* byte转为16进制
*
* @param bytes
* @return
*/
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length() == 1) {
//1得到一位的进行补0操作
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
/**
* 设置iv偏移量
* 本例采用ECB加密模式不需要设置iv偏移量
*/
private static final String IV_ = null;
/**
* 设置加密字符集
* 本例采用 UTF-8 字符集
*/
private static final String CHARACTER = "UTF-8";
/**
* 设置加密密码处理长度
* 不足此长度补0
*/
private static final int PWD_SIZE = 16;
/**
* 密码处理方法
* 如果加解密出问题
* 请先查看本方法排除密码长度不足填充0字节,导致密码不一致
* @param password 待处理的密码
* @return
* @throws UnsupportedEncodingException
*/
private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
byte[] data = null;
if (password != null) {
byte[] bytes = password.getBytes(CHARACTER);
if (password.length() < PWD_SIZE) {
System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
} else {
data = bytes;
}
}
return data;
}
//======================>原始加密<======================
/**
* 原始加密
* @param clearTextBytes 明文字节数组待加密的字节数组
* @param pwdBytes 加密密码字节数组
* @return 返回加密后的密文字节数组加密错误返回null
*/
public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
try {
// 1 获取加密密钥
SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
// 2 获取Cipher实例
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
// 查看数据块位数 默认为16byte * 8 =128 bit
// System.out.println("数据块位数(byte)" + cipher.getBlockSize());
// 3 初始化Cipher实例设置执行模式以及加密密钥
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// 4 执行
byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);
// 5 返回密文字符集
return cipherTextBytes;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 原始解密
* @param cipherTextBytes 密文字节数组待解密的字节数组
* @param pwdBytes 解密密码字节数组
* @return 返回解密后的明文字节数组解密错误返回null
*/
public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {
try {
// 1 获取解密密钥
SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
// 2 获取Cipher实例
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
// 查看数据块位数 默认为16byte * 8 =128 bit
// System.out.println("数据块位数(byte)" + cipher.getBlockSize());
// 3 初始化Cipher实例设置执行模式以及加密密钥
cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 4 执行
byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);
// 5 返回明文字符集
return clearTextBytes;
} catch (Exception e) {
e.printStackTrace();
}
// 解密错误 返回null
return null;
}
//======================>BASE64<======================
/**
* BASE64加密
* @param clearText 明文待加密的内容
* @param password 密码加密的密码
* @return 返回密文加密后得到的内容加密错误返回null
*/
public static String aesEncryptBase64(String clearText, String password) {
try {
// 1 获取加密密文字节数组
byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));
// 2 对密文字节数组进行BASE64 encoder 得到 BASE6输出的密文
BASE64Encoder base64Encoder = new BASE64Encoder();
// 3 返回BASE64输出的密文
return base64Encoder.encode(cipherTextBytes);
} catch (Exception e) {
e.printStackTrace();
}
// 加密错误 返回null
return null;
}
/**
* BASE64解密
* @param cipherText 密文带解密的内容
* @param password 密码解密的密码
* @return 返回明文解密后得到的内容解密错误返回null
*/
public static String aesDecryptBase64(String cipherText, String password) {
try {
// 1 BASE64输出的密文进行BASE64 decodebuffer 得到密文字节数组
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);
// 2 对密文字节数组进行解密 得到明文字节数组
byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));
// 3 根据 CHARACTER 转码返回明文字符串
return new String(clearTextBytes, CHARACTER);
} catch (Exception e) {
e.printStackTrace();
}
// 解密错误返回null
return null;
}
public static void main(String[] args) throws Exception {
// System.out.println(DigestUtils.sha256Hex("".getBytes()));
// String result = getSHA256StrJava("".getBytes());
// System.out.println(result);
// String hamacstr = HMACSHA256("WPS-4POST/callback/path/demoapplication/jsonWed, 20 Apr 2022 01:33:07 GMTfc005f51a6e75586d2d5d078b657dxxxdf9c1dfa6a7c0c0ba38c715daeb6ede9","cc2e3878f68e003347da63f9dbaee5a8");
// System.out.println(hamacstr);
//1.输出设置为base64时
String encryptedStr = aesEncryptBase64("123", "XDWe0nNGxTg2yD8Gb3uUapkoA8XtKvq3");//参数明文加密字符串
System.out.println("加密后的base64字符串为"+encryptedStr);
String decrypt = aesDecryptBase64(encryptedStr,"XDWe0nNGxTg2yD8Gb3uUapkoA8XtKvq3");//参数密文加密字符串
System.out.println("解密后的字符串为:" + decrypt);
}
}

View File

@ -0,0 +1,306 @@
package com.awspaas.user.apps.yiliwps.utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
public class HttpPostUtil {
/**
* 下载请求
*
* @param url
* @param headers
* @return
* @throws IOException
*/
public static void sendGetDownloadRequest(String url, Map<String, String> headers,String savePath) throws IOException {
// 设置请求头
HttpGet request = new HttpGet(url);
if (null != headers) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 发送http请求
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
if (null != entity) {
InputStream in = entity.getContent();
File file = new File(savePath);//这里为存储路径/xx/xx..
FileOutputStream fout = new FileOutputStream(file);
int a = -1;
byte[] tmp = new byte[1024];
while ((a = in.read(tmp)) != -1) {
fout.write(tmp, 0, a);
}
fout.flush();
fout.close();
in.close();
httpClient.close();
return;
}
throw new IOException("No response");
} catch (IOException e) {
throw e;
}
}
/**
* 发送Get请求(如果https请求需要忽略证书检测需自己实现)
*
* @param url
* @param headers
* @return
* @throws IOException
*/
public static String sendGetRequest(String url, Map<String, String> headers) throws IOException {
// 设置请求头
HttpGet request = new HttpGet(url);
if (null != headers) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 发送http请求
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
if (null != entity) {
String content = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(">>>输出"+content);
EntityUtils.consume(entity); // 关闭content stream
return content;
}
throw new IOException("No response");
} catch (IOException e) {
throw e;
}
}
/**
* 发送Get请求(如果https请求需要忽略证书检测需自己实现)
*/
public static <T> T sendPostRequest(String url, String body, Map<String, String> headers,Class<T> classes) throws IOException {
// 设置请求头
HttpPost request = new HttpPost(url);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求body
if (body != null) {
request.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
}
try {
// 发送http请求
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (null != entity) {
String content = EntityUtils.toString(entity);
httpClient.close();
response.close();
return JSON.parseObject(content,classes);
}
return null;
} catch (IOException e) {
throw e;
}
}
/**
* 发送Put请求(如果https请求需要忽略证书检测需自己实现)
*
* @param url
* @param headers
* @return
* @throws IOException
*/
public static CloseableHttpResponse sendPutRequest(String url, InputStream body, Map<String, String> headers) throws IOException {
// 设置请求头
HttpPut request = new HttpPut(url);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求body
if (body != null) {
InputStreamEntity entity = new InputStreamEntity(body);
entity.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());
request.setEntity(entity);
}
// 发送http请求
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
return httpClient.execute(request);
} catch (ClientProtocolException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
public static CloseableHttpResponse doPutUpload(String url, File file, Map<String, String> headers) {
FileInputStream fileInputStream = null;
CloseableHttpResponse response = null;
try {
// file
fileInputStream = new FileInputStream(file);
HttpPut httpput = new HttpPut(url);
addHeader(httpput, headers);
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
basicHttpEntity.setChunked(false);
basicHttpEntity.setContent(fileInputStream);
basicHttpEntity.setContentLength(file.length());
httpput.setEntity(basicHttpEntity);
response = executeRequest(url, httpput);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
}catch (Exception e1){
e1.printStackTrace();
}
}
}
return response;
}
private static void addHeader(HttpRequestBase httpRequestBase, Map<String, String> header) {
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpRequestBase.addHeader(entry.getKey(), entry.getValue());
}
}
}
private static CloseableHttpResponse executeRequest(String url, HttpUriRequest request) throws Exception {
return getInstance(url).execute(request);
}
private static CloseableHttpClient getInstance(String url) {
if (!StringUtils.isEmpty(url) && url.startsWith("https")) {
return sslClient();
} else {
return HttpClients.createDefault();
}
}
private static CloseableHttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", socketFactory).build();
// 创建ConnectionManager添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 发送Post请求(如果https请求需要忽略证书检测需自己实现)
*
* @param url
* @param headers
* @return
* @throws IOException
*/
public static Pair<StatusLine, String> sendPostRequest3(String url, String body, Map<String, String> headers) throws IOException {
// 设置请求头
HttpPost request = new HttpPost(url);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求body
if (body != null) {
request.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
}
// 发送http请求
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
if (null != entity) {
String content = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity); // 关闭content stream
return Pair.of(response.getStatusLine(), content);
}
throw new IOException("No response");
} catch (ClientProtocolException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
}

View File

@ -0,0 +1,167 @@
package com.awspaas.user.apps.yiliwps.utils;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.*;
public class WPS4Util {
public final static LogAPI log =SDK.getLogAPI();
public final static String HTTP_HEADER_WPS_DOCS_DATE = "Wps-Docs-Date";
public final static String HTTP_HEADER_WPS_DOCS_AUTHORIZATION = "Wps-Docs-Authorization";
public final static String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
public final static String WPS_SIGNATURE_VERSION = "WPS-4";
public final static String[] WORD_EXT = {"doc","dot","wps","wpt","docx","dotx","docm","dotm","rtf","txt"};
public final static String[] EXCEL_EXT = {"xls","xlt","et","xlsx","xltx","xlsm","xltm","csv"};
public final static String[] PPT_EXT = {"ppt","pptx","pptm","ppsx","ppsm","pps","potx","potm","dpt","dps"};
public final static String[] PDF_EXT = {"pdf", "ofd"};
public final static String[] X_EXT = {"jpeg","jpg","png","gif","bmp","tif","tiff","svg","psd",
"tar","zip","7z","gz","rar",
"md",
"c","cpp","java","js","css","lrc","h","asm","s","asp","bat","bas","prg","cmd","xml"};
private static String appId; // 应用id
private static String secretKey; // 应用秘钥
public static void initAppInfo(String appId, String secretKey) {
WPS4Util.appId = appId;
WPS4Util.secretKey = secretKey;
}
/**
* 根据文件名获取文件类型
* @param filename 文件名
* @return 文件类型 w p s f
*/
public static String getFileType(String filename){
if(StringUtils.isEmpty(filename)){
return null;
}
int index = filename.lastIndexOf('.');
if (index == -1){
return null;
}
String ext = filename.substring(index+1);
for (String element : WORD_EXT) {
if (StringUtils.equalsIgnoreCase(ext, element)) {
return "w";
}
}
for (String item : EXCEL_EXT) {
if (StringUtils.equalsIgnoreCase(ext, item)) {
return "s";
}
}
for (String value : PPT_EXT) {
if (StringUtils.equalsIgnoreCase(ext, value)) {
return "p";
}
}
for (String s : PDF_EXT) {
if (StringUtils.equalsIgnoreCase(ext, s)) {
return "f";
}
}
for (String s : X_EXT) {
if (StringUtils.equalsIgnoreCase(ext, s)) {
return "x";
}
}
return null;
}
/**
* 获取请求body MD5
* @param content 请求body
* @return
*/
private static String getContentSha256(String content) {
if (StringUtils.isBlank(content)) {
return "";
} else {
return DigestUtils.sha256Hex(content);
}
}
/**
* 获取日期字符串
*
* @param date
* @return
*/
private static String getGMTDateString(Date date) {
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss [GMT]", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format.format(date) + " GMT";
}
/**
* 获取WPS Authorization
* @param ver
* @param httpMethod
* @param uriWithQuerystring
* @param contentSha256
* @param dateString
* @param contentType
* @return
*/
private static String getWpsAuthorization(String ver,String httpMethod,String uriWithQuerystring, String contentSha256, String dateString, String contentType) throws Exception {
String signatureStr = String.format("%s%s%s%s%s%s",ver,httpMethod,
uriWithQuerystring,contentType,dateString,contentSha256);
//log.info("要签名的值:{}",signatureStr);
return String.format("WPS-4 %s:%s",appId,EncryptionUtil.HMACSHA256(signatureStr,secretKey));
}
public static String getRfc1123Date() {
SimpleDateFormat sdf4 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf4.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf4.format(new Date());
}
public static Map<String, String> getSignatureHeaders(String uriWithQuerystring,String httpMethod, String content, String contentType) throws Exception {
if (uriWithQuerystring == null) {
uriWithQuerystring = "";
}
if (contentType == null) {
contentType = "application/json";
}
String contentSha256 = getContentSha256(content);
String dateString = getRfc1123Date();//getGMTDateString(new Date());
String authorization = getWpsAuthorization(WPS_SIGNATURE_VERSION,httpMethod,
uriWithQuerystring,contentSha256, dateString, contentType);
Map<String, String> headers = new HashMap<>();
headers.put(WPS4Util.HTTP_HEADER_WPS_DOCS_AUTHORIZATION, authorization);
headers.put(WPS4Util.HTTP_HEADER_CONTENT_TYPE, contentType);
headers.put(WPS4Util.HTTP_HEADER_WPS_DOCS_DATE, dateString);
log.consoleInfo("签名结果: {} -> {}"+WPS4Util.HTTP_HEADER_WPS_DOCS_AUTHORIZATION+authorization);
//log.info("签名结果: {} -> {}",WPS4Util.HTTP_HEADER_CONTENT_TYPE,contentType);
//log.info("签名结果: {} -> {}",WPS4Util.HTTP_HEADER_WPS_DOCS_DATE,dateString);
return headers;
}
public static void main(String[] args) throws Exception {
String contentType = "application/json";
String uriWithQuerystring = "/api/edit/v1/files/1661841425405/link?type=w";
String body = "";
// 获取签名请求头
String appId = "AKyAYlPgfRjnFBGV";
String secretKey = "FPLVEBJfEsNVrBkBIShJAmwiufvJIqZy";
WPS4Util.initAppInfo(appId, secretKey);
Map<String, String> headers = WPS4Util.getSignatureHeaders(uriWithQuerystring, "GET",body, contentType);
for (Map.Entry<String, String> entry : headers.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(new Date()));
}
}

View File

@ -0,0 +1 @@
package com.awspaas.user.apps.yiliwps.utils; import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance; import com.actionsoft.bpms.commons.database.RowMapper; import com.actionsoft.bpms.commons.formfile.model.FormFileModel; import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile; import com.actionsoft.bpms.server.UserContext; import com.actionsoft.bpms.util.UtilString; import com.actionsoft.sdk.local.SDK; import com.awspaas.user.apps.yiliwps.constant.YiliWpsConst; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class WPSOnlineUtil { /** * 获取文件的后缀 * * @param fileName * @return */ public static String getSuffix(String fileName) { if (fileName.indexOf(".") == -1) { return ""; } return fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()); } /** * 获取WPS接口需要的文档类型 * @param fileName * @return */ public static String getFileType(String fileName){ String suffix = getSuffix(fileName).toLowerCase(); if(YiliWpsConst.SUPPORTTYPE_W.contains(suffix)){ return YiliWpsConst.WPS_FILETYPE_W; }else if(YiliWpsConst.SUPPORTTYPE_P.contains(suffix)){ return YiliWpsConst.WPS_FILETYPE_P; }else if(YiliWpsConst.SUPPORTTYPE_S.contains(suffix)){ return YiliWpsConst.WPS_FILETYPE_S; }else { return YiliWpsConst.WPS_FILETYPE_F; } } /** * 判断是否有编辑权限 * @param appId * @param field * @return */ public static String isHaveEditPermission(UserContext me, String appId, String field, String processInstId){ if(me.isMobileClient()){//手机端只读 return "read"; } if(!appId.equals("com.snowball.apps.contract")){//是否为合同管理 return "read"; } if(!field.equals("APPLYFILE") && !field.equals("MODULD_FILES")){ return "read"; } /** * 校验待办是否符合要求 */ String editProcessDefId = SDK.getAppAPI().getProperty(YiliWpsConst.APPID, "editProcessDefId"); if(UtilString.isNotEmpty(editProcessDefId)){ String[] split = editProcessDefId.split(","); String querySql = "("; for (String s : split) { querySql += " ACTIVITYDEFID = '"+s +"'"; querySql += " OR"; } querySql = querySql.substring(0,querySql.length()-2); querySql +=")"; List<TaskInstance> list = SDK.getTaskQueryAPI().activeTask().target(me.getUID()).processInstId(processInstId).addQuery(querySql,null).list(); if(null!= list && list.size()<=0){ return "read"; } } return "write"; } private class Mapper implements RowMapper<FormFile> { private Mapper() { } public FormFile mapRow(ResultSet rset, int rowNum) throws SQLException { FormFileModel model = new FormFileModel(); model.setId(rset.getString("ID")); model.setAppId(rset.getString("APPID")); model.setProcessInstId(rset.getString("PROCESSINSTID")); model.setTaskInstId(rset.getString("TASKINSTID")); model.setBoId(rset.getString("BOID")); model.setBoName(rset.getString("BONAME")); model.setBoItemName(rset.getString("BOFIELDNAME")); model.setCreateDate(rset.getTimestamp("CREATEDATE")); model.setCreateUser(rset.getString("CREATEUSER")); model.setFileName(rset.getString("FILENAME")); model.setFileSize(rset.getLong("FILESIZE")); model.setRemark(rset.getString("REMARK")); model.setExt1(rset.getString("EXT1")); model.setSecurityLevel(rset.getInt("SECURITYLEVEL")); model.setCloudInfo(rset.getString("CLOUDINFO")); model.setOrderIndex(rset.getInt("ORDERINDEX")); model.setGroupName(rset.getString("GROUPNAME")); return model; } } }

View File

@ -0,0 +1,311 @@
package com.awspaas.user.apps.yiliwps.web;
import com.actionsoft.apps.coe.pal.pal.repository.cache.PALRepositoryCache;
import com.actionsoft.apps.coe.pal.pal.repository.designer.CoeDesignerShapeAPIManager;
import com.actionsoft.apps.coe.pal.pal.repository.designer.manage.CoeDesignerAPIManager;
import com.actionsoft.apps.coe.pal.pal.repository.designer.model.BaseModel;
import com.actionsoft.apps.coe.pal.pal.repository.designer.util.CoeDesignerUtil;
import com.actionsoft.apps.coe.pal.pal.repository.designer.util.ShapeUtil;
import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryModel;
import com.actionsoft.apps.resource.plugin.profile.DCPluginProfile;
import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.formfile.dao.FormFileDao;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ActionWeb;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.conf.portal.AWSPortalConf;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.yiliwps.constant.YiliWpsConst;
import com.awspaas.user.apps.yiliwps.utils.CallASLPUtil;
import com.awspaas.user.apps.yiliwps.utils.HttpPostUtil;
import com.awspaas.user.apps.yiliwps.utils.WPS4Util;
import javax.ws.rs.HttpMethod;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
public class WpsWeb extends ActionWeb {
public final static LogAPI logAPI = SDK.getLogAPI();
public WpsWeb() {
super();
}
public WpsWeb(UserContext userContext) {
super(userContext);
}
/**
*
* @param
* @return
*/
public String getWPSOnlineFilePreviewUrl(String palId,String fileName) throws Exception{
//先判断该fileId有无附件
String querySql = " SELECT ID FROM " + YiliWpsConst.APP_ACT_COE_PAL_UPFILE+" WHERE PALREPOSITORYID = ? ORDER BY CREATETIME DESC";
String fileId = DBSql.getString(querySql, new Object[]{palId});
DCContext sourceDc = getFileDCContext(fileId,fileName);
WPS4Util.initAppInfo(YiliWpsConst.AK, YiliWpsConst.SK);
String url = String.format("/api/edit/v1/files/%s/link?type=%s&_w_third_sid=%s&_w_third_palId=%s&_w_third_queryFileId=%s&_w_third_fname=%s",fileId,"w",this.getContext().getSessionId(),palId,fileId,URLEncoder.encode(sourceDc.getFileName()));
Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.GET,null, YiliWpsConst.CONTENT_TYPE);
logAPI.consoleInfo(">>>>>headers"+headers);
return HttpPostUtil.sendGetRequest(YiliWpsConst.HOST+"/open"+url,headers);
}
public String getFileInfo(String sid,String palId,String fileId,String fileName){
String sourceFileName = null;
try {
sourceFileName = URLDecoder.decode(fileName,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
DCContext sourceDc = getFileDCContext(fileId,sourceFileName);
JSONObject jsonObject = new JSONObject();
JSONObject file = new JSONObject();
JSONObject user = new JSONObject();
JSONObject user_acl = new JSONObject();
JSONObject watermark = new JSONObject();
try {
file.put("id", fileId.equals("")?"1":fileId);
file.put("name", sourceFileName);
file.put("version", Integer.parseInt(SDK.getRuleAPI().executeAtScript("@sequence("+palId+")")));
long fileSize = 0;
if(sourceDc.existFile()){
fileSize = sourceDc.length();
}
file.put("size", fileSize==0 ? 20971520 : fileSize);
file.put("creator",super.getContext().getUID());
file.put("create_time",System.currentTimeMillis()/1000);
file.put("modifier", super.getContext().getUID());
file.put("modify_time", System.currentTimeMillis()/1000);
String downloadUrl = sourceDc.getDownloadURL();
downloadUrl = downloadUrl.replace("sid=ck", "sid="+sid);
downloadUrl = SDK.getAppAPI().getProperty(YiliWpsConst.APPID,"targetPortal")+ "/r"+ downloadUrl.substring(1,downloadUrl.length());
file.put("download_url", downloadUrl);
file.put("preview_pages", 0);
user_acl.put("read",1);
user_acl.put("update",1);
user_acl.put("download",1);
file.put("user_acl", user_acl);
user.put("id", super.getContext().getUID());
user.put("name", super.getContext().getUID());
user.put("logined",true);
//需要增加权限判断逻辑
//String haveEditPermission = WPSOnlineUtil.isHaveEditPermission(_uc,sourceAppId, boItemName, processInstId);
user.put("permission", "write");
user.put("avatar_url", "");
jsonObject.put("user", user);
//水印暂时不需要
/*watermark.put("type", UtilString.isEmpty(watermarkTxt)?0:1);//水印类型 0为无水印 1为文字水印
watermark.put("value", watermarkTxt); //文字水印的文字当type为1时此字段必选
watermark.put("fillstyle", watermarkColor);//水印的透明度非必选有默认值
watermark.put("font", watermarkFont);//水印的字体非必选有默认值
watermark.put("rotate", -0.7853982);//水印的旋转度非必选有默认值
watermark.put("horizontal",50); //水印水平间距非必选有默认值
watermark.put("vertical",100); //水印垂直间距非必选有默认值
file.put("watermark", watermark);*/
jsonObject.put("file", file);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("jsonObject = " + jsonObject);
return jsonObject.toString();
}
public String saveFileInfo(String save_type,String palId, String fileId,String sid,String fileName, File file){
UserContext me = UserContext.fromSessionId(sid);
JSONObject jsonObject = new JSONObject();
JSONObject fileJson = new JSONObject();
try {
FileInputStream fileInputStream=new FileInputStream(file);
//写入新文件
//调用刷新逻辑
CallASLPUtil aslpUtil =new CallASLPUtil();
aslpUtil.callTranslateDocASLP(me,palId,fileName,fileInputStream);
DCContext sourceDc = getFileDCContext(fileId,fileName);
sourceDc.setSession(me);
//在重新获取下fileId
String querySql = " SELECT ID FROM " + YiliWpsConst.APP_ACT_COE_PAL_UPFILE+" WHERE PALREPOSITORYID = ? ORDER BY CREATETIME DESC";
fileId = DBSql.getString(querySql, new Object[]{palId});
//整理返回的数据
fileJson.put("id", fileId);
fileJson.put("size", file.length());
fileJson.put("name", fileName);
fileJson.put("version", Integer.parseInt(SDK.getRuleAPI().executeAtScript("@sequence("+palId+")")));
String downloadUrl = sourceDc.getDownloadURL();
downloadUrl = downloadUrl.replace("sid=ck", "sid="+sid);
downloadUrl = SDK.getAppAPI().getProperty(YiliWpsConst.APPID,"targetPortal")+ "/r"+ downloadUrl.substring(1,downloadUrl.length());
fileJson.put("download_url", downloadUrl);
jsonObject.put("file",fileJson);
System.out.println("jsonObject.toString()1 = " + jsonObject.toString());
return jsonObject.toString();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("jsonObject.toString()2= " + jsonObject.toString());
return jsonObject.toString();
}
/**
* 获取历史版本文件
* @param params
* @return
*/
public String getHistoryFileInfo(JSONObject params){
JSONObject resultJson =new JSONObject();
JSONArray historyArray =new JSONArray();
String boId = params.getString("boId");
String boItemName = params.getString("boItemName").toString();
String sid = params.getString("sid");
UserContext uc = UserContext.fromSessionId(sid);
String sql = "SELECT * FROM WFC_FORMFILES WHERE BOID=? AND BOFIELDNAME=? ORDER BY ORDERINDEX DESC";
List<FormFile> list = DBSql.query(sql, new FormFileDao().rowMapper(), new Object[]{boId,boItemName});
if(null != list && list.size()>1){
for (int i = 1; i < list.size(); i++) {//因为第一个是现版本所以从第二个开始
JSONObject fileJson = new JSONObject();
FormFile formFile = list.get(i);
DCContext fileDCContext = SDK.getBOAPI().getFileDCContext(formFile);
fileDCContext.setSession(uc);
String fileName = fileDCContext.getFileName();
int orderIndex = formFile.getOrderIndex()+1;//wps历史版本从1开始
String id = formFile.getId();
long fileSize = formFile.getFileSize();
String downloadUrl = fileDCContext.getDownloadURL();
downloadUrl = downloadUrl.replace("sid=ck", "sid="+sid);
downloadUrl = AWSPortalConf.getUrl()+ "/r"+ downloadUrl.substring(1,downloadUrl.length());
downloadUrl += "%version=" +orderIndex;
long createTime = formFile.getCreateDate().getTime();
//获取编辑人信息
JSONObject userJson =new JSONObject();
String createUser = formFile.getCreateUser();
UserModel user = SDK.getORGAPI().getUser(createUser);
String userName = user.getUserName();
String userPhoto = SDK.getPortalAPI().getUserPhoto(uc, createUser);
String avatar_url = AWSPortalConf.getUrl() +"/r" + userPhoto.substring(1,userPhoto.length());
//组装json
userJson.put("id",createUser);
userJson.put("name",userName);
userJson.put("avatar_url",avatar_url);
fileJson.put("id",id);
fileJson.put("name",fileName);
fileJson.put("version",orderIndex);
fileJson.put("size",fileSize);
fileJson.put("download_url",downloadUrl);
fileJson.put("create_time",createTime);
fileJson.put("modify_time",createTime);
fileJson.put("creator",userJson);
fileJson.put("modifier",userJson);
historyArray.add(fileJson);
}
}
resultJson.put("histories",historyArray);
return resultJson.toString();
}
/**
* 获取指定版本文件
* @param params
*/
public String getVersionFileInfo(JSONObject params){
JSONObject resultJson =new JSONObject();
JSONObject fileJson =new JSONObject();
String boId = params.getString("boId");
String boItemName = params.getString("boItemName").toString();
String sid = params.getString("sid");
int version = params.getInteger("version");
UserContext uc = UserContext.fromSessionId(sid);
String sql = "SELECT * FROM WFC_FORMFILES WHERE BOID=? AND BOFIELDNAME=? AND ORDERINDEX = ? ORDER BY ORDERINDEX DESC";
List<FormFile> list = DBSql.query(sql, new FormFileDao().rowMapper(), new Object[]{boId,boItemName,version-1});
if(null !=list && list.size()>0){
FormFile formFile = list.get(0);
DCContext fileDCContext = SDK.getBOAPI().getFileDCContext(formFile);
fileDCContext.setSession(uc);
fileJson.put("id",formFile.getId());
fileJson.put("name",formFile.getFileName());
fileJson.put("version",version);
fileJson.put("size",formFile.getFileSize());
fileJson.put("create_time",formFile.getCreateDate().getTime());
fileJson.put("creator",formFile.getCreateUser());
fileJson.put("modify_time",formFile.getCreateDate().getTime());
fileJson.put("modifier",formFile.getCreateUser());
String downloadUrl = fileDCContext.getDownloadURL();
downloadUrl = downloadUrl.replace("sid=ck", "sid="+sid);
downloadUrl = AWSPortalConf.getUrl()+ "/r"+ downloadUrl.substring(1,downloadUrl.length());
fileJson.put("download_url",downloadUrl);
}
resultJson.put("file",fileJson);
return resultJson.toString();
}
/**
* 获取附件的附件ID
* @param palId
* @return
*/
public DCContext getFileDCContext(String palId,String fileName){
DCContext sourceDc = null;
//先判断该fileId有无附件
String querySql = " SELECT PALREPOSITORYID,SHAPEID,FILETYPE,FILENAME FROM " + YiliWpsConst.APP_ACT_COE_PAL_UPFILE+" WHERE ID = ? ORDER BY CREATETIME DESC";
RowMap model = DBSql.getMap(querySql, new Object[]{palId});
if(null != model){
DCPluginProfile dcProfile = DCProfileManager.getDCProfile(YiliWpsConst.FILE_APPID, YiliWpsConst.COE_UPFILE);
if (dcProfile != null) {
if ("f".equals(model.getString("FILETYPE"))) {// 文件
System.out.println(" >>>>进入普通文件" );
sourceDc = new DCContext(this.getContext(), dcProfile, YiliWpsConst.FILE_APPID, "file",
model.getString("PALREPOSITORYID"), model.getString("FILENAME"));
} else {// 图形
System.out.println(" >>>>进入图型文件" );
sourceDc = new DCContext(this.getContext(), dcProfile, YiliWpsConst.FILE_APPID, model.getString("PALREPOSITORYID"),
model.getString("SHAPEID"), model.getString("FILENAME"));
}
}
return sourceDc;
}else{//无附件则取打开默认模板
//先获取附件模版
System.out.println(" >>>>进入模版文件" );
String repositoryName = "!form-ui-file-";
BO bo = SDK.getBOAPI().query(YiliWpsConst.BO_EU_SYSTEM_DEMO_FILE).addQuery("FILESTATE=", true).detail();
List<FormFile> files = SDK.getBOAPI().getFiles(bo.getId(), "SYSTEMFILE");
FormFile formFile = files.get(0);
sourceDc = SDK.getBOAPI().getFileDCContext(formFile, repositoryName);
sourceDc.setSession(this.getContext());
//往附件表中写入一个附件
return sourceDc;
}
}
public String getCoeDefinition(String palId){
// coe所需参数
PALRepositoryModel plModel = PALRepositoryCache.getCache().get(palId);
String uuid = plModel.getId();
String fileName = ShapeUtil.replaceBlank(plModel.getName());
String wsid = plModel.getWsId();
String methodId = plModel.getMethodId();
BaseModel model = CoeDesignerAPIManager.getInstance().getDefinition(palId, 0);
if (model == null) {
model = CoeDesignerUtil.createModel(palId, 0);
}
CoeDesignerShapeAPIManager manager = CoeDesignerShapeAPIManager.getInstance();
String define = model.getDefinition();
//获取流程定义和排序
JSONObject object = manager.getCoeDefinitionAndSort(define, wsid, methodId);
model.setDefinition(object.getString("define"));
//处理流程节点形状的通用配置
JSONObject obj = manager.getCoeProcessShapeConfig(model.getDefinition(), wsid, methodId, palId);
model.setDefinition(obj.getString("define"));
model.setFileName(fileName);
return model.getDefinition();
}
}