Commit 7fd38335 by ys

项目初始化

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
.idea
\ No newline at end of file
`LoginService`中添加以下代码:
`LoginService`中添加以下代码:
```java
private static String getTokenFromHeader(HttpServletRequest request) {
return request.getHeader(LOGIN_IDENTITY_KEY);
}
```
```java
public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){
String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY);
// >----------------添加这部分代码----------------
if (!StringUtils.hasText(cookieToken)) {
cookieToken = getTokenFromHeader(request);
}
// ----------------添加这部分代码----------------<
if (cookieToken != null) {
...
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tbyf.util</groupId>
<artifactId>xxl-job-admin-client</artifactId>
<version>2.3.1</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<okhttp.version>4.10.0</okhttp.version>
<jackson.version>2.13.2.1</jackson.version>
<junit.version>5.9.3</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.tbyf.util;/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Miscellaneous methods for calculating digests.
*
* <p>Mainly for internal use within the framework; consider
* <a href="https://commons.apache.org/codec/">Apache Commons Codec</a>
* for a more comprehensive suite of digest utilities.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Craig Andrews
* @since 3.0
*/
public abstract class DigestUtils {
private static final String MD5_ALGORITHM_NAME = "MD5";
private static final char[] HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Calculate the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return the digest
*/
public static byte[] md5Digest(byte[] bytes) {
return digest(MD5_ALGORITHM_NAME, bytes);
}
/**
* Calculate the MD5 digest of the given stream.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return the digest
* @since 4.2
*/
public static byte[] md5Digest(InputStream inputStream) throws IOException {
return digest(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return a hexadecimal digest string
*/
public static String md5DigestAsHex(byte[] bytes) {
return digestAsHexString(MD5_ALGORITHM_NAME, bytes);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given stream.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the InputStream to calculate the digest over
* @return a hexadecimal digest string
* @since 4.2
*/
public static String md5DigestAsHex(InputStream inputStream) throws IOException {
return digestAsHexString(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* bytes to the given {@link StringBuilder}.
* @param bytes the bytes to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
*/
public static StringBuilder appendMd5DigestAsHex(byte[] bytes, StringBuilder builder) {
return appendDigestAsHex(MD5_ALGORITHM_NAME, bytes, builder);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* inputStream to the given {@link StringBuilder}.
* <p>This method does <strong>not</strong> close the input stream.
* @param inputStream the inputStream to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
* @since 4.2
*/
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException {
return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder);
}
/**
* Create a new {@link MessageDigest} with the given algorithm.
* <p>Necessary because {@code MessageDigest} is not thread-safe.
*/
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
}
private static byte[] digest(String algorithm, byte[] bytes) {
return getDigest(algorithm).digest(bytes);
}
private static byte[] digest(String algorithm, InputStream inputStream) throws IOException {
MessageDigest messageDigest = getDigest(algorithm);
if (inputStream instanceof UpdateMessageDigestInputStream){
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
return messageDigest.digest();
}
else {
final byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
messageDigest.update(buffer, 0, bytesRead);
}
return messageDigest.digest();
}
}
private static String digestAsHexString(String algorithm, byte[] bytes) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return new String(hexDigest);
}
private static String digestAsHexString(String algorithm, InputStream inputStream) throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return new String(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, byte[] bytes, StringBuilder builder) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return builder.append(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, InputStream inputStream, StringBuilder builder)
throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return builder.append(hexDigest);
}
private static char[] digestAsHexChars(String algorithm, byte[] bytes) {
byte[] digest = digest(algorithm, bytes);
return encodeHex(digest);
}
private static char[] digestAsHexChars(String algorithm, InputStream inputStream) throws IOException {
byte[] digest = digest(algorithm, inputStream);
return encodeHex(digest);
}
private static char[] encodeHex(byte[] bytes) {
char[] chars = new char[32];
for (int i = 0; i < chars.length; i = i + 2) {
byte b = bytes[i / 2];
chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
chars[i + 1] = HEX_CHARS[b & 0xf];
}
return chars;
}
}
package com.tbyf.util;
public class TriggerLog {
private int triggerId;
private int executorId;
private int jobId;
private String executorAddress;
private String executionParam;
private String executorHandler;
private int retryCount;
private String triggerTime;
private int triggerCode;
private String triggerMsg;
private String handleTime;
private int handleCode;
private String handleMsg;
private int alarmStatus;
public int getTriggerId() {
return triggerId;
}
public void setTriggerId(int triggerId) {
this.triggerId = triggerId;
}
public int getExecutorId() {
return executorId;
}
public void setExecutorId(int executorId) {
this.executorId = executorId;
}
public int getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
public String getExecutorAddress() {
return executorAddress;
}
public void setExecutorAddress(String executorAddress) {
this.executorAddress = executorAddress;
}
public String getExecutionParam() {
return executionParam;
}
public void setExecutionParam(String executionParam) {
this.executionParam = executionParam;
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
public String getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(String triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
}
public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public String getHandleTime() {
return handleTime;
}
public void setHandleTime(String handleTime) {
this.handleTime = handleTime;
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
}
package com.tbyf.util;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
abstract class UpdateMessageDigestInputStream extends InputStream {
UpdateMessageDigestInputStream() {
}
public void updateMessageDigest(MessageDigest messageDigest) throws IOException {
int data;
while((data = this.read()) != -1) {
messageDigest.update((byte)data);
}
}
public void updateMessageDigest(MessageDigest messageDigest, int len) throws IOException {
int data;
for(int bytesRead = 0; bytesRead < len && (data = this.read()) != -1; ++bytesRead) {
messageDigest.update((byte)data);
}
}
}
package com.tbyf.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class XxlJobAdminClient {
private static final OkHttpClient client = new OkHttpClient();
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final String TOKEN_HEADER_NAME = "XXL_JOB_LOGIN_IDENTITY";
private final String adminUrl;
private final String token;
public XxlJobAdminClient(String adminUrl, String username, String password) {
if (!adminUrl.endsWith("/")) {
adminUrl = adminUrl + "/";
}
this.adminUrl = adminUrl;
this.token = buildToken(username, password);
}
private static String buildToken(String username, String password) {
String token = "";
try {
HashMap<String, Object> map = new HashMap<>();
map.put("username", username);
map.put("password", DigestUtils.md5DigestAsHex(password.getBytes()));
token = new BigInteger(objectMapper.writeValueAsString(map).getBytes()).toString(16);
} catch (JsonProcessingException ignored) {
}
return token;
}
private List<Object> postForm(String path, FormBody formBody, ResponseHandler handler) throws Exception {
Request request = new Request.Builder()
.url(adminUrl + path)
.post(formBody)
.header(TOKEN_HEADER_NAME, token)
.build();
try (Response response = client.newCall(request).execute()) {
ArrayList<Object> result = new ArrayList<>();
if (handler != null) {
handler.handler(response, result);
}
return result;
}
}
/**
* 新增任务
*
* @return 任务id, 返回null则表示创建失败
*/
public Integer addJob(int executorId,
String jobDesc,
String author,
String alarmEmail,
String cronEx,
String jobHandler,
String param) {
FormBody formBody = new FormBody.Builder()
.add("jobGroup", String.valueOf(executorId))
.add("jobDesc", jobDesc)
.add("author", author)
.add("alarmEmail", alarmEmail)
.add("scheduleType", "CRON")
.add("scheduleConf", cronEx)
.add("misfireStrategy", "DO_NOTHING")
.add("executorRouteStrategy", "ROUND")
.add("executorHandler", jobHandler)
.add("executorParam", param)
.add("executorBlockStrategy", "SERIAL_EXECUTION")
.add("executorTimeout", "0")
.add("executorFailRetryCount", "0")
.add("glueType", "BEAN")
.add("glueRemark", "GLUE代码初始化")
.build();
try {
return (Integer) postForm("jobinfo/add", formBody, (response, list) -> {
ResponseBody responseBody = response.body();
if (responseBody != null) {
Result result = objectMapper.readValue(responseBody.string(), Result.class);
String jobId = (String) result.getContent();
list.add(Integer.parseInt(jobId));
}
}).get(0);
} catch (Exception e) {
return null;
}
}
/**
* 立即执行一次任务
*/
public void trigger(int jobId, String param) {
FormBody formBody = new FormBody.Builder()
.add("id", String.valueOf(jobId))
.add("executorParam", param)
.build();
try {
postForm("jobinfo/trigger", formBody, null);
} catch (Exception e) {
}
}
public List<TriggerLog> getTriggerLogs(int jobId, String from, String to, int offset, int limit) {
return doGetTriggerLogs(jobId, -1, from, to, offset, limit);
}
public List<TriggerLog> getSuccessfulTriggerLogs(int jobId, String from, String to, int offset, int limit) {
return doGetTriggerLogs(jobId, 1, from, to, offset, limit);
}
public List<TriggerLog> getFailureTriggerLogs(int jobId, String from, String to, int offset, int limit) {
return doGetTriggerLogs(jobId, 2, from, to, offset, limit);
}
public List<TriggerLog> getUncompletedTriggerLogs(int jobId, String from, String to, int offset, int limit) {
return doGetTriggerLogs(jobId, 3, from, to, offset, limit);
}
@SuppressWarnings("unchecked")
private List<TriggerLog> doGetTriggerLogs(
/*int executorId,*/
int jobId,
int status,
String from,
String to,
int offset, // from 0
int limit) {
try {
FormBody formBody = new FormBody.Builder()
.add("jobGroup", "0")
.add("jobId", String.valueOf(jobId))
.add("logStatus", String.valueOf(status))
.add("filterTime", from + " - " + to)
.add("start", String.valueOf(offset))
.add("length", String.valueOf(limit))
.build();
return (List<TriggerLog>) postForm("joblog/pageList", formBody, (response, list) -> {
ResponseBody responseBody = response.body();
if (responseBody != null) {
PageResult result = objectMapper.readValue(responseBody.string(), PageResult.class);
List<TriggerLog> triggerLogs = result.getData().stream()
.map(e -> {
Map<String, Object> map = (Map<String, Object>) e;
TriggerLog triggerLog = new TriggerLog();
triggerLog.setTriggerId((Integer) map.get("id"));
triggerLog.setExecutorId((Integer) map.get("jobGroup"));
triggerLog.setJobId((Integer) map.get("jobId"));
triggerLog.setExecutorAddress((String) map.get("executorAddress"));
triggerLog.setExecutionParam((String) map.get("executorParam"));
triggerLog.setExecutorHandler((String) map.get("executorHandler"));
triggerLog.setRetryCount((Integer) map.get("executorFailRetryCount"));
triggerLog.setTriggerTime((String) map.get("triggerTime"));
triggerLog.setTriggerCode((Integer) map.get("triggerCode"));
triggerLog.setTriggerMsg((String) map.get("triggerMsg"));
triggerLog.setHandleTime((String) map.get("handleTime"));
triggerLog.setHandleCode((Integer) map.get("handleCode"));
triggerLog.setHandleMsg((String) map.get("handleMsg"));
triggerLog.setAlarmStatus((Integer) map.get("alarmStatus"));
return triggerLog;
}).collect(Collectors.toList());
list.add(triggerLogs);
}
}).get(0);
} catch (Exception e) {
return Collections.emptyList();
}
}
@FunctionalInterface
interface ResponseHandler {
void handler(Response response, List<Object> list) throws Exception;
}
private static class Result {
private int code;
private String msg;
private Object content;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
}
public static class PageResult {
private List<Object> data;
private int recordsFiltered;
private int recordsTotal;
public List<Object> getData() {
return data;
}
public void setData(List<Object> data) {
this.data = data;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public int getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(int recordsTotal) {
this.recordsTotal = recordsTotal;
}
}
}
package com.tbyf.util;
import org.junit.jupiter.api.Test;
import java.util.List;
class XxlJobAdminClientTest {
XxlJobAdminClient adminClient =
new XxlJobAdminClient("http://localhost:8080/xxl-job-admin/",
"admin",
"123456");
@Test
void addJob() {
Integer jobId = adminClient.addJob(
2,
"测试",
"CPA",
"",
"5/5 * * * * ?",
"SampleHandler1",
"");
System.out.println("jobId = " + jobId);
}
@Test
void trigger() {
adminClient.trigger(4, "1");
}
@Test
void getTriggerLogs() {
List<TriggerLog> triggerLogs = adminClient.getTriggerLogs(
4,
"2024-05-15 00:00:00",
"2024-05-15 23:59:59",
0,
2);
triggerLogs.forEach(log -> System.out.println(log.getTriggerId() + ": " + log.getTriggerMsg()));
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment