环境准备
- IntelliJ IDEA并安装
Plugin DevKit
插件 - JDK8
基于Gradle创建plugin项目
File->New->Projects
Next
Next
Next && Finish
修改build.gradle
文件
打开build.gradle
文件可以查看到当前idea版本是2018.3.6
。且可以看到idea推荐的Gradle版本为4.10
此时项目在自动构建时会失败,因为gradle-intellij-plugin
版本为1.3.1
和Gradle版本不匹配,需要修改合适的gradle-intellij-plugin
版本。根据gradle-intellij-plugin查看到4.10
的Gradle可以使用0.7.3
的gradle-intellij-plugin
build.gradle
修改后项目构建成功
至此,我们项目插件项目创建完成了。
翻译插件
创建Action
查看创建结果
编写翻译逻辑
public void actionPerformed(AnActionEvent e) {
Editor editor = e.getDataContext().getData(CommonDataKeys.EDITOR);
String q = editor.getSelectionModel().getSelectedText();
String appId = "20190717000318901";
String appKey = "R8OPnhJn7TP2m2n4g7za";
String salt = RandomUtil.randomNumbers(3);
MD5 md5 = MD5.create();
String sign = md5.digestHex(appId + q + salt + appKey);
String transUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";
HttpGet httpGet = new HttpGet(transUrl + "?q=" + q
+ "&from=en&to=zh"
+ "&appid=" + appId
+ "&salt=" + salt
+ "&sign=" + sign);
try (CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String text = new BufferedReader(new InputStreamReader(content, StandardCharsets.UTF_8))
.lines().collect(Collectors.joining("\n"));
ResultSet resultSet = JSONUtil.toBean(text, ResultSet.class);
if (CollUtil.isNotEmpty(resultSet.getTrans_result())) {
Notifications.Bus.notify(buildNotification(resultSet.getTrans_result().get(0).getDst(), NotificationType.INFORMATION));
}
} catch (Exception ex) {
//
}
}
private Notification buildNotification(String content, NotificationType type) {
String groupDisplayId = "translation";
Notification notification = new Notification(groupDisplayId, null, type);
notification.setContent(content);
return notification;
}
runIde & 测试
插件安装
buildPlugin
install
选择生成的zip文件后,重启idea即可。