基于JFinal中搭建wopi协议支撑办法

1、添加maven依赖

 <dependency>
            <groupId>com.github.icecooly</groupId>
            <artifactId>FastHttpClient</artifactId>
            <version>1.7</version>
 </dependency>
 

2、FastHttpClient示例
https://gitee.com/icecooly/FastHttpClient

3、在 Jfinal的Start.java中配置

/**
* 配置路由
 */
public void configRoute(Routes me) {
    me.add("/baseService/wopiImpl", WopiController.class);
}
    

4、Handler控制器

package com.demo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WopiHandler extends com.jfinal.handler.Handler {
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        String[] actionParams = target.split("/");
        int arParmsLength = 6;
        String wopi="wopi";
        String prefix="/baseService/wopiImpl/";
        //1、变更jfinal的路由--->get文件下载请求
        if (actionParams.length == arParmsLength && actionParams[2].equals(wopi) && actionParams[3].equals("files")
                && actionParams[5].equals("contents") && request.getMethod().equals("GET")) {
            target=prefix+"download";
        }
        //2、保存修改内容
        else if(actionParams.length == arParmsLength && actionParams[2].equals(wopi) && actionParams[3].equals("files")
                && actionParams[5].equals("contents") && request.getMethod().equals("POST"))
        {
            target=prefix+"save";
        }
        //3、获取文件内容
        else if(actionParams.length == arParmsLength-1 && actionParams[2].equals(wopi) && actionParams[3].equals("files")
                && request.getMethod().equals("GET"))
        {
            target=prefix+"getInfo";
        }
        next.handle(target, request, response, isHandled);
    }
}

 

5、WopiController.java

package com.demo.blog;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class WopiController extends Controller {
    private String filePath = "D:\\Work\\";


    /**
     * 功能:配合wopi协议,提供文件下载
     * 作者:黄海
     * 时间:2019-08-17
     * 用例:   http://127.0.0.1/baseService/wopi/files/123.docx/contents
     */
    @Before({GET.class})
    public void download() {
        String filename = getRequest().getRequestURI().split("/")[4];
        renderFile(new File(filePath + filename));
    }

    /**
     * 功能:配合wopi协议,获取文件的信息
     * 作者:黄海
     * 时间:2019-08-17
     * 用例:http://127.0.0.1/baseService/wopi/files/123.docx
     */
    @Before({GET.class})
    public void getInfo() throws IOException, NoSuchAlgorithmException {
        String filename = getRequest().getRequestURI().split("/")[4];
        File file = new File(filePath + filename);
        Kv kv = Kv.by("BaseFileName", file.getName())
                .set("OwnerId", "admin")
                .set("Size", file.length())
                .set("SHA256", getHash256(file))
                .set("Version", file.lastModified())
                .set("AllowExternalMarketplace", true)
                .set("UserCanWrite", true)
                .set("SupportsUpdate", true)
                .set("SupportsLocks", true);
        renderJson(kv);
    }

    /**
     * 功能:配合wopi协议,对修改后的文件进行保存
     * 作者:黄海
     * 时间:2019-08-17
     */
    @Before({POST.class})
    public void save() throws IOException, ServletException {
        String filename = getRequest().getRequestURI().split("/")[4];
        HttpServletRequest request=getRequest();
        ServletInputStream is=request.getInputStream();
        File file = new File(filePath+filename);
        FileOutputStream os = new FileOutputStream(file);
        byte[] bb = new byte[1024];
        int ch;
        while ((ch = is.read(bb)) > -1) {
            os.write(bb, 0, ch);
        }
        os.close();
        is.close();
        renderNull();
    }

    /**
     * 获取文件的SHA-256值
     *
     * @param file
     * @return
     */
    @NotAction
    private String getHash256(File file) throws IOException, NoSuchAlgorithmException {
        String value = "";
        try (InputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int numRead;
            // 返回实现指定摘要算法的 MessageDigest 对象
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            do {
                numRead = fis.read(buffer);
                if (numRead > 0) {
                    // 更新摘要
                    digest.update(buffer, 0, numRead);
                }
            } while (numRead != -1);

            value = new String(Base64.getEncoder().encode(digest.digest()));
        }
        return value;
    }

}

6、测试类

package com.demo.blog;

import io.itit.itf.okhttp.*;
import io.itit.itf.okhttp.util.FileUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.File;
import java.io.InputStream;


public class WopiTest {
    /*

     */
    public static void main(String[] args) throws Exception {
        //1、测试下载文件
        String url = "http://127.0.0.1/baseService/wopi/files/123.docx/contents";
        testDownload(url);

        url = "http://127.0.0.1:8080/wopi/files/123.docx/contents";
        testDownload(url);


        //2、获取文件信息
        url = "http://127.0.0.1/baseService/wopi/files/123.docx";
        testGetInfo(url);

        url = "http://127.0.0.1:8080/wopi/files/123.docx";
        testGetInfo(url);

        //3、测试修改文件信息
        url = "http://127.0.0.1/baseService/wopi/files/1234.docx/contents";
        testSave(url);

        url = "http://127.0.0.1:8080/wopi/files/1234.docx/contents";
        testSave(url);
    }

    /**
     * 功能:测试下载文件
     */
    static void testDownload(String url) throws Exception {
        String savePath = "c:\\123.docx";
        InputStream is = FastHttpClient.get().url(url).build().execute().byteStream();
        FileUtil.saveContent(is, new File(savePath));
    }

    /**
     * 功能:测试获取文件信息
     */
    static void testGetInfo(String url) throws Exception {
        String resp = FastHttpClient.get().url(url).build().execute().string();
        System.out.println(resp);
    }

    /**
     * 功能:测试修改功能
     * 作者:黄海
     * 时间:2019-08-17
     *
     * @return
     * @throws Exception
     */
    static void testSave(String url) throws Exception {
        String fileName = "项目通知.docx";
        String filePath = "D:\\日常工作\\" + fileName;
        byte[] fileContent = FileUtil.getBytes(filePath);
        //原生方式
        MediaType JSON = MediaType.parse("application/octet-stream");
        RequestBody body = RequestBody.create(JSON, fileContent);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}

 

posted @ 2019-08-17 12:00  糖豆爸爸  阅读(451)  评论(0编辑  收藏  举报
Live2D