Low-code integrated Java series: Efficiently build custom plug-ins

Preface

As software development develops rapidly and demands continue to grow, developers face more pressure and challenges. Traditional development methods require a lot of time and energy, and the emergence of low-code development platforms provides developers with a more efficient and faster development method. Today, the editor will take building a command plug-in as an example to show how to use the Java language to efficiently build a custom plug-in.

Environmental preparation

  • Movable type grid plug-in building tool-Java version (forguncyJavaPluginGenerator)
  • Movable type grid designer (v10.0 version and above)
  • IDE compiler (e.g. IntelliJ IDEA Community Edition)
  • Java Runtime Environment
  • JDK8.0 version and above

plugin generator

Open the Forguncy Java Plugin Generator tool-Java version link ( forguncyJavaPluginGenerator ) and download the [Forguncy Java Plugin Generator]. It is recommended to use the compressed package version.

Open [forguncyJavaExtensionGenerateTool.exe] and configure the basic information of the plug-in in the following interface:

Click to create the server command plug-in. After the creation is completed, the project file will be generated in the corresponding directory set:

Next, use the IDE compiler to open the MyPlugin project. After opening, the project directory is as shown below:

At this point, the preliminary preparation work has been completed. Next, we will write the code logic.

Code

Add dependencies

Before implementing the code, we first need to add some dependencies related to the movable type grid. As shown below, we need to add the following dependencies to the pom file:

Just replace Icon.png and PluginLogo.png with the plug-in’s icon and logo.

And [PluginConfig.json] is used to configure basic plug-in information:

{
  "assembly": [],                                    // 如需要加载其他类
  "javascript": [],                                  // 如需加载其他JavaScript文件
  "css": [],                                         // 如需加载其他css文件
  "image": "resources/PluginLogo.png",               // 需要加载图片的相对路径
  "description": "这是一个活字格插件",                 // 插件的文本描述信息
  "description_cn": "这是一个活字格插件",              // 插件的中文文本描述信息
  "name": "MyPlugin",                                // 插件名称
  "name_cn": "我的插件",                              // 插件中午名称
  "pluginType": "command",                           // 插件类型,当前为命令类型插件
  "guid": "fefeb164-ab98-48c8-b309-b5410052e504",    // 插件唯一标识GUID,建议勿修改
  "version": "1.0.0.0",                              // 插件版本
  "dependenceVersion": "10.0.0.0"                    // 插件支持依赖最低活字格版本
}

Write core code logic

After completing the above configuration, you can write the plug-in logic. The following is a sample code of the plug-in, which mainly generates a random number signature through 5 parameters (AppSecret, request ID, timestamp, data and signature result).

package org.example;

import com.grapecity.forguncy.LoggerContext;
import com.grapecity.forguncy.commands.ICommandExecutableInServerSide;
import com.grapecity.forguncy.commands.IServerCommandExecuteContext;
import com.grapecity.forguncy.commands.annotation.ResultToProperty;
import com.grapecity.forguncy.commands.annotation.common.Category;
import com.grapecity.forguncy.commands.entity.Command;
import com.grapecity.forguncy.commands.entity.ExecuteResult;
import com.grapecity.forguncy.commands.enumeration.CommandScope;
import com.grapecity.forguncy.plugincommon.common.annotation.*;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;

@Data
@Icon( uri= "resources/Icon.png")
@Category(category = "程杰合集")
public class MyPlugin extends Command implements ICommandExecutableInServerSide {

    private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    @DisplayName(displayName = "AppSecret")
    @FormulaProperty
    @Required
    private String appSecret;

    @DisplayName(displayName = "请求ID")
    @FormulaProperty
    @Required
    private String requestId;

    @DisplayName(displayName = "时间戳")
    @FormulaProperty
    @Required
    private String timestamp;

    @DisplayName(displayName = "数据")
    @FormulaProperty
    @Required
    private String data;

    @ResultToProperty
    @FormulaProperty
    @DisplayName(displayName = "签名结果")
    private String resultTo = "结果";

    @Override
    public ExecuteResult execute(IServerCommandExecuteContext dataContext) {
        Long innerTimestamp = Long.parseLong(timestamp);
        String res = null;
        try {
            res = sign(appSecret, requestId, innerTimestamp, data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            dataContext.getParameters().put(resultTo, res);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        ExecuteResult executeResult = new ExecuteResult();
        executeResult.getReturnValues().put("结果", res);
        return executeResult;
    }

    @Override
    public boolean getDesignerPropertyVisible(String propertyName, CommandScope commandScope) {

        return super.getDesignerPropertyVisible(propertyName, commandScope);
    }

    @Override
    public String toString() {
        return "签名程杰";
    }

    public static String sign(String appSecret, String requestId, Long timestamp, String data) throws Exception{
        // 1.签名参数按自然升序排列,拼接上data
        StringBuilder sb = new StringBuilder();
        sb.append("appSecret=").append(appSecret).append("&")
                .append("requestId=").append(requestId).append("&")
                .append("timestamp=").append(timestamp)
                .append(data);
        // 2.对签名字符串base64编码后获取32位md5值
        // 2.对签名字符串base64编码后获取32位md5值
        String base64Encode = base64Encode(sb.toString().getBytes("UTF-8"));
        String md5Value = md5(base64Encode);
        // 3.将得到的MD5值进行sha1散列,转换为16进制字符串
        String sign = sha1(md5Value);
        return sign;
    }

    /**
     * 对字符串进行MD5加密,得到32位MD5值
     * @param text 明文
     * @return 密文
     */
    public static String md5(String text) {
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("MD5");
            msgDigest.update(text.getBytes("UTF-8"));
            byte[] bytes = msgDigest.digest();
            // 转成16进制
            return new String(encodeHex(bytes));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("System doesn't support your  EncodingException.");
        }
    }

    /***
     * SHA加密
     * @return
     */
    public static String sha1(String content) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        byte[] byteArray = content.getBytes("UTF-8");
        return new String(encodeHex(sha.digest(byteArray)));
    }


    /**
     * base64编码
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String base64Encode(byte[] content) throws Exception {
        return Base64.encodeBase64String(content).replaceAll("(\\\r\\\n|\\\r|\\\n|\\\n\\\r)", "");
    }

    /**
     * base64解码
     *
     * @param content
     * @return
     * @throws Exception
     */

    public static byte[] base64Decode(String content) throws Exception {
        return Base64.decodeBase64(content);
    }

    /**
     * 转换成16进制
     * @param data
     * @return
     */
    private static char[] encodeHex(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS[0x0F & data[i]];
        }
        return out;
    }
    public static String getPostData(HttpServletRequest request) {
        StringBuilder data = new StringBuilder();
        String line;
        BufferedReader reader;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
        } catch (IOException e) {
            return null;
        }
        return data.toString();
    }
}

Use maven to package plug-ins

After the code is written, package the entire project: click [clean] here, and then click [install]:

Then the packaged product will appear in the [target] directory:

Then install the packaged zip plug-in into the movable type grid designer and use it.

Create a new command and you can find the plug-in you just packaged in the command selection.

Fill in the parameters:

This can be tested in the server-side command:

As you can see, a random number signature is returned in the test results above. In this way, a plug-in built using Java language has been developed.

Summarize

The above is the whole process of how to use Java to develop a command plug-in in a low-code platform. If you want to know more information, please click here to view.

Extension link:

From form-driven to model-driven, interpret the development trend of low-code development platforms

What is a low-code development platform?

Branch-based version management helps low-code move from project delivery to customized product development

Fellow chicken "open sourced" deepin-IDE and finally achieved bootstrapping! Good guy, Tencent has really turned Switch into a "thinking learning machine" Tencent Cloud's April 8 failure review and situation explanation RustDesk remote desktop startup reconstruction Web client WeChat's open source terminal database based on SQLite WCDB ushered in a major upgrade TIOBE April list: PHP fell to an all-time low, Fabrice Bellard, the father of FFmpeg, released the audio compression tool TSAC , Google released a large code model, CodeGemma , is it going to kill you? It’s so good that it’s open source - open source picture & poster editor tool
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/powertoolsteam/blog/11052465