proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/ntp/NtpCollectImpl.java
|
NtpCollectImpl
|
collect
|
class NtpCollectImpl extends AbstractCollect {
public NtpCollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {<FILL_FUNCTION_BODY>}
private Map<String, String> getNtpInfo(TimeInfo timeInfo) {
Map<String, String> valueMap = new HashMap<>(16);
TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
Date date = timeStamp.getDate();
NtpV3Packet message = timeInfo.getMessage();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
valueMap.put("time", Long.toString(timeStamp.getTime()));
valueMap.put("date", simpleDateFormat.format(date));
valueMap.put("offset", Long.toString(timeInfo.getOffset()));
valueMap.put("delay", Long.toString(timeInfo.getDelay()));
valueMap.put("version", Integer.toString(message.getVersion()));
valueMap.put("mode", Integer.toString(message.getMode()));
valueMap.put("stratum", Integer.toString(message.getStratum()));
valueMap.put("referenceId", String.valueOf(message.getReferenceId()));
valueMap.put("precision", Integer.toString(message.getPrecision()));
return valueMap;
}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_NTP;
}
}
|
long startTime = System.currentTimeMillis();
if (metrics == null || metrics.getNtp() == null) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("NTP collect must have NTP params");
return;
}
NtpProtocol ntpProtocol = metrics.getNtp();
String host = ntpProtocol.getHost();
int timeout = CollectUtil.getTimeout(ntpProtocol.getTimeout());
NTPUDPClient client = null;
try {
client = new NTPUDPClient();
client.setDefaultTimeout(timeout);
client.open();
InetAddress serverAddress = InetAddress.getByName(host);
TimeInfo timeInfo = client.getTime(serverAddress);
long responseTime = System.currentTimeMillis() - startTime;
timeInfo.computeDetails();
// 获取ntp服务器信息
Map<String, String> resultMap = getNtpInfo(timeInfo);
resultMap.put(CollectorConstants.RESPONSE_TIME, Long.toString(responseTime));
List<String> aliasFields = metrics.getAliasFields();
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String field : aliasFields) {
String fieldValue = resultMap.get(field);
valueRowBuilder.addColumns(Objects.requireNonNullElse(fieldValue, CommonConstants.NULL_VALUE));
}
builder.addValues(valueRowBuilder.build());
client.close();
} catch (SocketException socketException) {
String errorMsg = CommonUtil.getMessageFromThrowable(socketException);
log.debug(errorMsg);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("NTPUDPClient open is fail: " + errorMsg);
} catch (UnknownHostException unknownHostException) {
String errorMsg = CommonUtil.getMessageFromThrowable(unknownHostException);
log.debug(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("NTPServerAddress is unknownHost: " + errorMsg);
} catch (IOException ioException) {
String errorMsg = CommonUtil.getMessageFromThrowable(ioException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Receive timed out: " + timeout + "ms");
} catch (Exception e) {
String errorMsg = CommonUtil.getMessageFromThrowable(e);
log.warn(errorMsg, e);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
} finally {
if (client != null) {
try {
client.close();
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
| 396
| 726
| 1,122
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/pop3/Pop3CollectImpl.java
|
Pop3CollectImpl
|
createPOP3Client
|
class Pop3CollectImpl extends AbstractCollect {
private final static String EMAIL_COUNT = "email_count";
private final static String MAILBOX_SIZE = "mailbox_size";
public Pop3CollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {
long startTime = System.currentTimeMillis();
try {
validateParams(metrics);
} catch (Exception e) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(e.getMessage());
return;
}
Pop3Protocol pop3Protocol = metrics.getPop3();
POP3Client pop3Client = null;
boolean ssl = Boolean.parseBoolean(pop3Protocol.getSsl());
try {
pop3Client = createPOP3Client(pop3Protocol, ssl);
if (pop3Client.isConnected()) {
long responseTime = System.currentTimeMillis() - startTime;
obtainPop3Metrics(builder, pop3Client, metrics.getAliasFields(),
responseTime);
} else {
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed,Timeout " + pop3Protocol.getTimeout() + "ms");
}
} catch (IOException e1) {
String errorMsg = CommonUtil.getMessageFromThrowable(e1);
log.info(errorMsg);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
} catch (Exception e2) {
String errorMsg = CommonUtil.getMessageFromThrowable(e2);
log.info(errorMsg);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
} finally {
if (pop3Client != null) {
try {
pop3Client.logout();
pop3Client.disconnect();
} catch (IOException e) {
String errorMsg = CommonUtil.getMessageFromThrowable(e);
log.info(errorMsg);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
}
}
}
}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_POP3;
}
/**
* 校验参数
* @param metrics metrics
* @throws Exception exception
*/
private void validateParams(Metrics metrics) throws Exception {
Pop3Protocol pop3Protocol = metrics.getPop3();
if (metrics == null || pop3Protocol == null || pop3Protocol.isInvalid()) {
throw new Exception("Pop3 collect must has pop3 params");
}
}
/**
* 创建POP3连接【支持SSL加密】
* @param pop3Protocol pop3 Protocol
* @param ssl ssl
* @return return
* @throws IOException IO Exception
*/
private POP3Client createPOP3Client(Pop3Protocol pop3Protocol, boolean ssl) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 获取Pop3指标信息
* @param builder builder
* @param pop3Client pop3 client
* @param aliasFields alias Fields
* @param responseTime response Time
*/
private void obtainPop3Metrics(CollectRep.MetricsData.Builder builder, POP3Client pop3Client,
List<String> aliasFields, long responseTime) throws IOException {
Map<String, Object> pop3Metrics = parsePop3Metrics(pop3Client, aliasFields);
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String alias : aliasFields) {
Object value = pop3Metrics.get(alias);
if (value != null) {
valueRowBuilder.addColumns(String.valueOf(value));
} else {
if (CollectorConstants.RESPONSE_TIME.equalsIgnoreCase(alias)) {
valueRowBuilder.addColumns(String.valueOf(responseTime));
} else {
valueRowBuilder.addColumns(CommonConstants.NULL_VALUE);
}
}
}
builder.addValues(valueRowBuilder);
}
private Map<String, Object> parsePop3Metrics(POP3Client pop3Client, List<String> aliasFields) throws IOException {
Map<String, Object> pop3Metrics = new HashMap<>(aliasFields.size());
POP3MessageInfo status = pop3Client.status();
int emailCount = 0;
double mailboxSize = 0.0;
if (status != null) {
emailCount = status.number;
// byte -> kb
mailboxSize = (double) status.size / 1024.0;
pop3Metrics.put(EMAIL_COUNT, emailCount);
pop3Metrics.put(MAILBOX_SIZE, mailboxSize);
}
return pop3Metrics;
}
}
|
POP3Client pop3Client = null;
// 判断是否启用 SSL 加密连接
if (ssl) {
pop3Client = new POP3SClient(true);
} else {
pop3Client = new POP3Client();
}
// 设置超时时间
int timeout = Integer.parseInt(pop3Protocol.getTimeout());
if (timeout > 0) {
pop3Client.setConnectTimeout(timeout);
}
pop3Client.setCharset(StandardCharsets.UTF_8);
// 连接到POP3服务器
String host = pop3Protocol.getHost();
int port = Integer.parseInt(pop3Protocol.getPort());
pop3Client.connect(host, port);
// 验证凭据
String email = pop3Protocol.getEmail();
String authorize = pop3Protocol.getAuthorize();
boolean isAuthenticated = pop3Client.login(email, authorize);
if (!isAuthenticated) {
throw new Exception("Pop3 client authentication failed");
}
return pop3Client;
| 1,269
| 274
| 1,543
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/push/PushCollectImpl.java
|
PushCollectImpl
|
parseResponse
|
class PushCollectImpl extends AbstractCollect {
private static Map<Long, Long> timeMap = new ConcurrentHashMap<>();
// ms
private static final Integer timeout = 3000;
private static final Integer SUCCESS_CODE = 200;
// 第一次采集多久之前的数据,其实没有办法确定,因为无法确定上次何时采集,难以避免重启后重复采集的现象,默认30s
private static final Integer firstCollectInterval = 30000;
public PushCollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder,
long monitorId, String app, Metrics metrics) {
long curTime = System.currentTimeMillis();
PushProtocol pushProtocol = metrics.getPush();
Long time = timeMap.getOrDefault(monitorId, curTime - firstCollectInterval);
timeMap.put(monitorId, curTime);
HttpContext httpContext = createHttpContext(pushProtocol);
HttpUriRequest request = createHttpRequest(pushProtocol, monitorId, time);
try {
CloseableHttpResponse response = CommonHttpClient.getHttpClient().execute(request, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != SUCCESS_CODE) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("StatusCode " + statusCode);
return;
}
String resp = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
parseResponse(builder, resp, metrics);
} catch (Exception e) {
String errorMsg = CommonUtil.getMessageFromThrowable(e);
log.error(errorMsg, e);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
}
}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_PUSH;
}
private HttpContext createHttpContext(PushProtocol pushProtocol) {
HttpHost host = new HttpHost(pushProtocol.getHost(), Integer.parseInt(pushProtocol.getPort()));
HttpClientContext httpClientContext = new HttpClientContext();
httpClientContext.setTargetHost(host);
return httpClientContext;
}
private HttpUriRequest createHttpRequest(PushProtocol pushProtocol, Long monitorId, Long startTime) {
RequestBuilder requestBuilder = RequestBuilder.get();
// uri
String uri = CollectUtil.replaceUriSpecialChar(pushProtocol.getUri());
if (IpDomainUtil.isHasSchema(pushProtocol.getHost())) {
requestBuilder.setUri(pushProtocol.getHost() + ":" + pushProtocol.getPort() + uri);
} else {
String ipAddressType = IpDomainUtil.checkIpAddressType(pushProtocol.getHost());
String baseUri = CollectorConstants.IPV6.equals(ipAddressType)
? String.format("[%s]:%s", pushProtocol.getHost(), pushProtocol.getPort() + uri)
: String.format("%s:%s", pushProtocol.getHost(), pushProtocol.getPort() + uri);
requestBuilder.setUri(CollectorConstants.HTTP_HEADER + baseUri);
}
requestBuilder.addHeader(HttpHeaders.CONNECTION, "keep-alive");
requestBuilder.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36");
requestBuilder.addParameter("id", String.valueOf(monitorId));
requestBuilder.addParameter("time", String.valueOf(startTime));
requestBuilder.addHeader(HttpHeaders.ACCEPT, "application/json");
//requestBuilder.setUri(pushProtocol.getUri());
if (timeout > 0) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setRedirectsEnabled(true)
.build();
requestBuilder.setConfig(requestConfig);
}
return requestBuilder.build();
}
private void parseResponse(CollectRep.MetricsData.Builder builder, String resp, Metrics metric) {<FILL_FUNCTION_BODY>}
}
|
Message<PushMetricsDto> msg = JsonUtil.fromJson(resp, new TypeReference<Message<PushMetricsDto>>() {
});
if (msg == null) {
throw new NullPointerException("parse result is null");
}
PushMetricsDto pushMetricsDto = msg.getData();
if (pushMetricsDto == null || pushMetricsDto.getMetricsList() == null) {
throw new NullPointerException("parse result is null");
}
for (PushMetricsDto.Metrics pushMetrics : pushMetricsDto.getMetricsList()) {
List<CollectRep.ValueRow> rows = new ArrayList<>();
for (Map<String, String> metrics : pushMetrics.getMetrics()) {
List<String> metricColumn = new ArrayList<>();
for (Metrics.Field field : metric.getFields()) {
metricColumn.add(metrics.get(field.getField()));
}
CollectRep.ValueRow valueRow = CollectRep.ValueRow.newBuilder()
.addAllColumns(metricColumn).build();
rows.add(valueRow);
}
builder.addAllValues(rows);
}
builder.setTime(System.currentTimeMillis());
| 1,122
| 301
| 1,423
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/smtp/SmtpCollectImpl.java
|
SmtpCollectImpl
|
collect
|
class SmtpCollectImpl extends AbstractCollect {
public SmtpCollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {<FILL_FUNCTION_BODY>}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_SMTP;
}
private static Map<String, String> execCmdAndParseResult(SMTP smtp, String cmd, SmtpProtocol smtpProtocol) throws IOException {
Map<String, String> result = new HashMap<>(8);
// 存入smtp连接的响应
result.put("smtpBanner", smtp.getReplyString());
smtp.helo(smtpProtocol.getEmail());
// 获取helo的响应
String replyString = smtp.getReplyString();
result.put("heloInfo", replyString);
String[] lines = replyString.split("\n");
for (String line : lines) {
if (line.startsWith("250")) {
result.put("response", "OK");
}
}
return result;
}
}
|
long startTime = System.currentTimeMillis();
if (metrics == null || metrics.getSmtp() == null) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("Smtp collect must has Smtp params");
return;
}
SmtpProtocol smtpProtocol = metrics.getSmtp();
String host = smtpProtocol.getHost();
String port = smtpProtocol.getPort();
int timeout = CollectUtil.getTimeout(smtpProtocol.getTimeout());
SMTP smtp = null;
try {
smtp = new SMTP();
smtp.setConnectTimeout(timeout);
smtp.setCharset(StandardCharsets.UTF_8);
smtp.connect(host, Integer.parseInt(port));
if (smtp.isConnected()) {
long responseTime = System.currentTimeMillis() - startTime;
List<String> aliasFields = metrics.getAliasFields();
Map<String, String> resultMap = execCmdAndParseResult(smtp, smtpProtocol.getCmd(), smtpProtocol);
resultMap.put(CollectorConstants.RESPONSE_TIME, Long.toString(responseTime));
if (resultMap.size() < aliasFields.size()) {
log.error("smtp response data not enough: {}", resultMap);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("The cmd execution results do not match the expected number of metrics.");
return;
}
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String field : aliasFields) {
String fieldValue = resultMap.get(field);
valueRowBuilder.addColumns(Objects.requireNonNullElse(fieldValue, CommonConstants.NULL_VALUE));
}
builder.addValues(valueRowBuilder.build());
} else {
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed,Timeout " + timeout + "ms");
return;
}
smtp.disconnect();
} catch (SocketException socketException) {
String errorMsg = CommonUtil.getMessageFromThrowable(socketException);
log.debug(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("The peer refused to connect: service port does not listening or firewall: " + errorMsg);
} catch (IOException ioException) {
String errorMsg = CommonUtil.getMessageFromThrowable(ioException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed: " + errorMsg);
} catch (Exception e) {
String errorMsg = CommonUtil.getMessageFromThrowable(e);
log.warn(errorMsg, e);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
} finally {
if (smtp != null) {
try {
smtp.disconnect();
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
| 297
| 797
| 1,094
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/strategy/CollectStrategyFactory.java
|
CollectStrategyFactory
|
run
|
class CollectStrategyFactory implements CommandLineRunner {
/**
* strategy container
*/
private static final ConcurrentHashMap<String, AbstractCollect> COLLECT_STRATEGY = new ConcurrentHashMap<>();
/**
* get instance of this protocol collection
* @param protocol collect protocol
* @return implement of Metrics Collection
*/
public static AbstractCollect invoke(String protocol) {
return COLLECT_STRATEGY.get(protocol);
}
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// spi load and registry protocol and collect instance
ServiceLoader<AbstractCollect> loader = ServiceLoader.load(AbstractCollect.class, AbstractCollect.class.getClassLoader());
for (AbstractCollect collect : loader) {
COLLECT_STRATEGY.put(collect.supportProtocol(), collect);
}
| 148
| 77
| 225
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/telnet/TelnetCollectImpl.java
|
TelnetCollectImpl
|
execCmdAndParseResult
|
class TelnetCollectImpl extends AbstractCollect {
public TelnetCollectImpl(){}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {
long startTime = System.currentTimeMillis();
if (metrics == null || metrics.getTelnet() == null) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("Telnet collect must has telnet params");
return;
}
TelnetProtocol telnet = metrics.getTelnet();
int timeout = CollectUtil.getTimeout(telnet.getTimeout());
TelnetClient telnetClient = null;
try {
telnetClient = new TelnetClient("vt200");
telnetClient.setConnectTimeout(timeout);
telnetClient.connect(telnet.getHost(), Integer.parseInt(telnet.getPort()));
if (telnetClient.isConnected()) {
long responseTime = System.currentTimeMillis() - startTime;
List<String> aliasFields = metrics.getAliasFields();
Map<String, String> resultMap = execCmdAndParseResult(telnetClient, telnet.getCmd());
resultMap.put(CollectorConstants.RESPONSE_TIME, Long.toString(responseTime));
if (resultMap.size() < aliasFields.size()) {
log.error("telnet response data not enough: {}", resultMap);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("The cmd execution results do not match the expected number of metrics.");
return;
}
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String field : aliasFields) {
String fieldValue = resultMap.get(field);
valueRowBuilder.addColumns(Objects.requireNonNullElse(fieldValue, CommonConstants.NULL_VALUE));
}
builder.addValues(valueRowBuilder.build());
} else {
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed,Timeout " + timeout + "ms");
return;
}
telnetClient.disconnect();
} catch (ConnectException connectException) {
String errorMsg = CommonUtil.getMessageFromThrowable(connectException);
log.debug(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("The peer refused to connect: service port does not listening or firewall: " + errorMsg);
} catch (IOException ioException) {
String errorMsg = CommonUtil.getMessageFromThrowable(ioException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed: " + errorMsg);
} catch (Exception e) {
String errorMsg = CommonUtil.getMessageFromThrowable(e);
log.warn(errorMsg, e);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
} finally {
if (telnetClient != null) {
try {
telnetClient.disconnect();
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_TELNET;
}
private static Map<String, String> execCmdAndParseResult(TelnetClient telnetClient, String cmd) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (cmd == null || cmd.trim().length() == 0) {
return new HashMap<>(16);
}
OutputStream outputStream = telnetClient.getOutputStream();
outputStream.write(cmd.getBytes());
outputStream.flush();
String result = new String(telnetClient.getInputStream().readAllBytes());
String[] lines = result.split("\n");
boolean contains = lines[0].contains("=");
return Arrays.stream(lines)
.map(item -> {
if (contains) {
return item.split("=");
} else {
return item.split("\t");
}
})
.filter(item -> item.length == 2)
.collect(Collectors.toMap(x -> x[0], x -> x[1]));
| 908
| 208
| 1,116
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/udp/UdpCollectImpl.java
|
UdpCollectImpl
|
collect
|
class UdpCollectImpl extends AbstractCollect {
private static final byte[] HELLO = "hello".getBytes(StandardCharsets.UTF_8);
public UdpCollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {<FILL_FUNCTION_BODY>}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_UDP;
}
}
|
long startTime = System.currentTimeMillis();
if (metrics == null || metrics.getUdp() == null) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("Udp collect must has udp params");
return;
}
UdpProtocol udpProtocol = metrics.getUdp();
int timeout = CollectUtil.getTimeout(udpProtocol.getTimeout());
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(timeout);
String content = udpProtocol.getContent();
byte[] buffer = CollectUtil.fromHexString(content);
buffer = buffer == null ? HELLO : buffer;
SocketAddress socketAddress = new InetSocketAddress(udpProtocol.getHost(), Integer.parseInt(udpProtocol.getPort()));
DatagramPacket request = new DatagramPacket(buffer, buffer.length, socketAddress);
socket.send(request);
byte[] responseBuffer = new byte[1];
DatagramPacket response = new DatagramPacket(responseBuffer, responseBuffer.length);
socket.receive(response);
long responseTime = System.currentTimeMillis() - startTime;
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String alias : metrics.getAliasFields()) {
if (CollectorConstants.RESPONSE_TIME.equalsIgnoreCase(alias)) {
valueRowBuilder.addColumns(Long.toString(responseTime));
} else {
valueRowBuilder.addColumns(CommonConstants.NULL_VALUE);
}
}
builder.addValues(valueRowBuilder.build());
} catch (SocketTimeoutException timeoutException) {
String errorMsg = CommonUtil.getMessageFromThrowable(timeoutException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed: " + errorMsg);
} catch (PortUnreachableException portUnreachableException) {
String errorMsg = CommonUtil.getMessageFromThrowable(portUnreachableException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_REACHABLE);
builder.setMsg("Peer port unreachable");
} catch (Exception exception) {
String errorMsg = CommonUtil.getMessageFromThrowable(exception);
log.warn(errorMsg, exception);
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg(errorMsg);
}
| 127
| 631
| 758
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/collect/websocket/WebsocketCollectImpl.java
|
WebsocketCollectImpl
|
send
|
class WebsocketCollectImpl extends AbstractCollect {
public WebsocketCollectImpl() {
}
@Override
public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {
long startTime = System.currentTimeMillis();
if (metrics == null || metrics.getWebsocket() == null) {
builder.setCode(CollectRep.Code.FAIL);
builder.setMsg("Websocket collect must has Websocket params");
return;
}
WebsocketProtocol websocketProtocol = metrics.getWebsocket();
String host = websocketProtocol.getHost();
String port = websocketProtocol.getPort();
Socket socket = null;
try {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(host, Integer.parseInt(port));
socket.connect(socketAddress);
if (socket.isConnected()) {
long responseTime = System.currentTimeMillis() - startTime;
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
send(out);
Map<String, String> resultMap = readHeaders(in);
resultMap.put(CollectorConstants.RESPONSE_TIME, Long.toString(responseTime));
// 关闭输出流和Socket连接
in.close();
out.close();
socket.close();
List<String> aliasFields = metrics.getAliasFields();
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
for (String field : aliasFields) {
String fieldValue = resultMap.get(field);
valueRowBuilder.addColumns(Objects.requireNonNullElse(fieldValue, CommonConstants.NULL_VALUE));
}
builder.addValues(valueRowBuilder.build());
} else {
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Peer connect failed:");
}
} catch (UnknownHostException unknownHostException) {
String errorMsg = CommonUtil.getMessageFromThrowable(unknownHostException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("UnknownHost:" + errorMsg);
} catch (SocketTimeoutException socketTimeoutException) {
String errorMsg = CommonUtil.getMessageFromThrowable(socketTimeoutException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Socket connect timeout: " + errorMsg);
} catch (IOException ioException) {
String errorMsg = CommonUtil.getMessageFromThrowable(ioException);
log.info(errorMsg);
builder.setCode(CollectRep.Code.UN_CONNECTABLE);
builder.setMsg("Connect may fail:" + errorMsg);
}
}
@Override
public String supportProtocol() {
return DispatchConstants.PROTOCOL_WEBSOCKET;
}
private static void send(OutputStream out) throws IOException {<FILL_FUNCTION_BODY>}
// 读取响应头
private static Map<String, String> readHeaders(InputStream in) throws IOException {
Map<String, String> map = new HashMap<>(8);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null && !line.isEmpty()) {
int separatorIndex = line.indexOf(':');
if (separatorIndex != -1) {
String key = line.substring(0, separatorIndex).trim();
String value = line.substring(separatorIndex + 1).trim();
// 首字母小写化
map.put(StringUtils.uncapitalize(key), value);
} else {
// 切割HTTP/1.1, 101, Switching Protocols
String[] parts = line.split("\\s+", 3);
if (parts.length == 3) {
for (int i = 0; i < parts.length; i++) {
if (parts[i].startsWith("HTTP")) {
map.put("httpVersion", parts[i]);
} else if (Character.isDigit(parts[i].charAt(0))) {
map.put("responseCode", parts[i]);
} else {
map.put("statusMessage", parts[i]);
}
}
}
}
}
return map;
}
private static byte[] generateRandomKey() {
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
return key;
}
private static String base64Encode(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
}
|
byte[] key = generateRandomKey();
String base64Key = base64Encode(key);
String requestLine = "GET / HTTP/1.1\r\n";
out.write(requestLine.getBytes());
String hostName = InetAddress.getLocalHost().getHostAddress();
out.write(("Host:" + hostName + "\r\n").getBytes());
out.write("Upgrade: websocket\r\n".getBytes());
out.write("Connection: Upgrade\r\n".getBytes());
out.write("Sec-WebSocket-Version: 13\r\n".getBytes());
out.write("Sec-WebSocket-Extensions: chat, superchat\r\n".getBytes());
out.write(("Sec-WebSocket-Key: " + base64Key + "\r\n").getBytes());
out.write("Content-Length: 0\r\n".getBytes());
out.write("\r\n".getBytes());
out.flush();
| 1,235
| 254
| 1,489
|
<methods>public non-sealed void <init>() ,public abstract void collect(org.apache.hertzbeat.common.entity.message.CollectRep.MetricsData.Builder, long, java.lang.String, org.apache.hertzbeat.common.entity.job.Metrics) ,public abstract java.lang.String supportProtocol() <variables>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/WorkerPool.java
|
WorkerPool
|
initWorkExecutor
|
class WorkerPool implements DisposableBean {
private ThreadPoolExecutor workerExecutor;
public WorkerPool() {
initWorkExecutor();
}
private void initWorkExecutor() {<FILL_FUNCTION_BODY>}
/**
* Run the collection task thread
*
* @param runnable Task
* @throws RejectedExecutionException when thread pool full
*/
public void executeJob(Runnable runnable) throws RejectedExecutionException {
workerExecutor.execute(runnable);
}
@Override
public void destroy() throws Exception {
if (workerExecutor != null) {
workerExecutor.shutdownNow();
}
}
}
|
// thread factory
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setUncaughtExceptionHandler((thread, throwable) -> {
log.error("[Important] WorkerPool workerExecutor has uncaughtException.", throwable);
log.error("Thread Name {} : {}", thread.getName(), throwable.getMessage(), throwable);
})
.setDaemon(true)
.setNameFormat("collect-worker-%d")
.build();
workerExecutor = new ThreadPoolExecutor(100,
1024,
10,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
| 179
| 176
| 355
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/CollectServer.java
|
CollectNettyEventListener
|
onChannelActive
|
class CollectNettyEventListener implements NettyEventListener {
@Override
public void onChannelActive(Channel channel) {<FILL_FUNCTION_BODY>}
@Override
public void onChannelIdle(Channel channel) {
log.info("handle idle event triggered. collector is going offline.");
}
}
|
String identity = CollectServer.this.collectJobService.getCollectorIdentity();
String mode = CollectServer.this.collectJobService.getCollectorMode();
CollectorInfo collectorInfo = CollectorInfo.builder()
.name(identity)
.ip(IpDomainUtil.getLocalhostIp())
.mode(mode)
// todo more info
.build();
timerDispatch.goOnline();
// send online message
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setIdentity(identity)
.setType(ClusterMsg.MessageType.GO_ONLINE)
.setMsg(JsonUtil.toJson(collectorInfo))
.build();
CollectServer.this.sendMsg(message);
if (scheduledExecutor == null) {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setUncaughtExceptionHandler((thread, throwable) -> {
log.error("HeartBeat Scheduler has uncaughtException.");
log.error(throwable.getMessage(), throwable);
})
.setDaemon(true)
.setNameFormat("heartbeat-worker-%d")
.build();
scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
// schedule send heartbeat message
scheduledExecutor.scheduleAtFixedRate(() -> {
try {
ClusterMsg.Message heartbeat = ClusterMsg.Message.newBuilder()
.setIdentity(identity)
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.HEARTBEAT)
.build();
CollectServer.this.sendMsg(heartbeat);
log.info("collector send cluster server heartbeat, time: {}.", System.currentTimeMillis());
} catch (Exception e) {
log.error("schedule send heartbeat to server error.{}", e.getMessage());
}
}, 5, 5, TimeUnit.SECONDS);
}
| 80
| 491
| 571
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/internal/CollectJobService.java
|
CollectJobService
|
collectSyncOneTimeJobData
|
class CollectJobService {
private static final String COLLECTOR_STR = "-collector";
private final TimerDispatch timerDispatch;
private final WorkerPool workerPool;
private final String collectorIdentity;
private String mode = null;
private CollectServer collectServer;
public CollectJobService(TimerDispatch timerDispatch, DispatchProperties properties, WorkerPool workerPool) {
this.timerDispatch = timerDispatch;
this.workerPool = workerPool;
if (properties != null && properties.getEntrance() != null && properties.getEntrance().getNetty() != null
&& properties.getEntrance().getNetty().isEnabled()) {
mode = properties.getEntrance().getNetty().getMode();
String collectorName = properties.getEntrance().getNetty().getIdentity();
if (StringUtils.hasText(collectorName)) {
collectorIdentity = collectorName;
} else {
collectorIdentity = IpDomainUtil.getCurrentHostName() + COLLECTOR_STR;
log.info("user not config this collector identity, use [host name - host ip] default: {}.", collectorIdentity);
}
} else {
collectorIdentity = CommonConstants.MAIN_COLLECTOR_NODE;
}
}
/**
* Execute a one-time collection task and get the collected data response
* 执行一次性采集任务,获取采集数据响应
*
* @param job Collect task details 采集任务详情
* @return Collection results 采集结果
*/
public List<CollectRep.MetricsData> collectSyncJobData(Job job) {
final List<CollectRep.MetricsData> metricsData = new LinkedList<>();
final CountDownLatch countDownLatch = new CountDownLatch(1);
CollectResponseEventListener listener = new CollectResponseEventListener() {
@Override
public void response(List<CollectRep.MetricsData> responseMetrics) {
if (responseMetrics != null) {
metricsData.addAll(responseMetrics);
}
countDownLatch.countDown();
}
};
timerDispatch.addJob(job, listener);
try {
countDownLatch.await(120, TimeUnit.SECONDS);
} catch (Exception e) {
log.info("The sync task runs for 120 seconds with no response and returns");
}
return metricsData;
}
/**
* Execute a one-time collection task and send the collected data response
*
* @param oneTimeJob Collect task details 采集任务详情
*/
public void collectSyncOneTimeJobData(Job oneTimeJob) {<FILL_FUNCTION_BODY>}
/**
* Issue periodic asynchronous collection tasks
* 下发周期性异步采集任务
*
* @param job Collect task details 采集任务详情
*/
public void addAsyncCollectJob(Job job) {
timerDispatch.addJob(job.clone(), null);
}
/**
* Cancel periodic asynchronous collection tasks
* 取消周期性异步采集任务
*
* @param jobId Job ID 采集任务ID
*/
public void cancelAsyncCollectJob(Long jobId) {
if (jobId != null) {
timerDispatch.deleteJob(jobId, true);
}
}
/**
* send async collect response data
*
* @param metricsData collect data
*/
public void sendAsyncCollectData(CollectRep.MetricsData metricsData) {
String data = ProtoJsonUtil.toJsonStr(metricsData);
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setIdentity(collectorIdentity)
.setMsg(data)
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.RESPONSE_CYCLIC_TASK_DATA)
.build();
this.collectServer.sendMsg(message);
}
public String getCollectorIdentity() {
return collectorIdentity;
}
public String getCollectorMode() {
return mode;
}
public void setCollectServer(CollectServer collectServer) {
this.collectServer = collectServer;
}
}
|
workerPool.executeJob(() -> {
List<CollectRep.MetricsData> metricsDataList = this.collectSyncJobData(oneTimeJob);
List<String> jsons = new ArrayList<>(metricsDataList.size());
for (CollectRep.MetricsData metricsData : metricsDataList) {
String json = ProtoJsonUtil.toJsonStr(metricsData);
if (json != null) {
jsons.add(json);
}
}
String response = JsonUtil.toJson(jsons);
ClusterMsg.Message message = ClusterMsg.Message.newBuilder()
.setMsg(response)
.setDirection(ClusterMsg.Direction.REQUEST)
.setType(ClusterMsg.MessageType.RESPONSE_ONE_TIME_TASK_DATA)
.build();
this.collectServer.sendMsg(message);
});
| 1,081
| 218
| 1,299
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/CollectCyclicDataProcessor.java
|
CollectCyclicDataProcessor
|
handle
|
class CollectCyclicDataProcessor implements NettyRemotingProcessor {
private final CollectServer collectServer;
public CollectCyclicDataProcessor(CollectServer collectServer) {
this.collectServer = collectServer;
}
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
Job job = JsonUtil.fromJson(message.getMsg(), Job.class);
if (job == null) {
log.error("collector receive cyclic task job is null");
return null;
}
collectServer.getCollectJobService().addAsyncCollectJob(job);
return null;
| 96
| 78
| 174
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/DeleteCyclicTaskProcessor.java
|
DeleteCyclicTaskProcessor
|
handle
|
class DeleteCyclicTaskProcessor implements NettyRemotingProcessor {
private final CollectServer collectServer;
public DeleteCyclicTaskProcessor(CollectServer collectServer) {
this.collectServer = collectServer;
}
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<Long>> typeReference = new TypeReference<>() {};
List<Long> jobIds = JsonUtil.fromJson(message.getMsg(), typeReference);
if (jobIds == null || jobIds.isEmpty()) {
log.error("collector receive delete cyclic task job ids is null");
return null;
}
for (Long jobId : jobIds) {
collectServer.getCollectJobService().cancelAsyncCollectJob(jobId);
}
return null;
| 96
| 125
| 221
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/GoCloseProcessor.java
|
GoCloseProcessor
|
handle
|
class GoCloseProcessor implements NettyRemotingProcessor {
private final CollectServer collectServer;
private TimerDispatch timerDispatch;
public GoCloseProcessor(final CollectServer collectServer) {
this.collectServer = collectServer;
}
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
if (this.timerDispatch == null) {
this.timerDispatch = SpringContextHolder.getBean(TimerDispatch.class);
}
if (message.getMsg().contains(CommonConstants.COLLECTOR_AUTH_FAILED)) {
log.error("[Auth Failed]receive client auth failed message and go close. {}", message.getMsg());
}
this.timerDispatch.goOffline();
this.collectServer.shutdown();
SpringApplication.exit(SpringContextHolder.getApplicationContext(), () -> 0);
SpringContextHolder.shutdown();
log.info("receive offline message and close success");
return null;
| 102
| 167
| 269
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/GoOfflineProcessor.java
|
GoOfflineProcessor
|
handle
|
class GoOfflineProcessor implements NettyRemotingProcessor {
private TimerDispatch timerDispatch;
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
if (this.timerDispatch == null) {
this.timerDispatch = SpringContextHolder.getBean(TimerDispatch.class);
}
timerDispatch.goOffline();
log.info("receive offline message and handle success");
message.getMsg();
if (message.getMsg().contains(CommonConstants.COLLECTOR_AUTH_FAILED)) {
log.error("[Auth Failed]receive client auth failed message and go offline. {}", message.getMsg());
return null;
}
return ClusterMsg.Message.newBuilder()
.setIdentity(message.getIdentity())
.setDirection(ClusterMsg.Direction.RESPONSE)
.setMsg(String.valueOf(CommonConstants.SUCCESS_CODE))
.build();
| 69
| 196
| 265
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/GoOnlineProcessor.java
|
GoOnlineProcessor
|
handle
|
class GoOnlineProcessor implements NettyRemotingProcessor {
private TimerDispatch timerDispatch;
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
if (this.timerDispatch == null) {
this.timerDispatch = SpringContextHolder.getBean(TimerDispatch.class);
}
timerDispatch.goOnline();
log.info("receive online message and handle success");
return ClusterMsg.Message.newBuilder()
.setIdentity(message.getIdentity())
.setDirection(ClusterMsg.Direction.RESPONSE)
.setMsg(String.valueOf(CommonConstants.SUCCESS_CODE))
.build();
| 68
| 127
| 195
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/entrance/processor/HeartbeatProcessor.java
|
HeartbeatProcessor
|
handle
|
class HeartbeatProcessor implements NettyRemotingProcessor {
@Override
public ClusterMsg.Message handle(ChannelHandlerContext ctx, ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
}
|
log.info("collector receive manager server response heartbeat, time: {}. ", System.currentTimeMillis());
return null;
| 53
| 35
| 88
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/HashedWheelTimer.java
|
HashedWheelTimeout
|
expire
|
class HashedWheelTimeout implements Timeout {
private static final int ST_INIT = 0;
private static final int ST_CANCELLED = 1;
private static final int ST_EXPIRED = 2;
private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state");
private final HashedWheelTimer timer;
private final TimerTask task;
private final long deadline;
@SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization"})
private volatile int state = ST_INIT;
/**
* RemainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the
* HashedWheelTimeout will be added to the correct HashedWheelBucket.
*/
long remainingRounds;
/**
* This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list.
* As only the workerThread will act on it there is no need for synchronization / volatile.
*/
HashedWheelTimeout next;
HashedWheelTimeout prev;
/**
* The bucket to which the timeout was added
*/
HashedWheelBucket bucket;
HashedWheelTimeout(HashedWheelTimer timer, TimerTask task, long deadline) {
this.timer = timer;
this.task = task;
this.deadline = deadline;
}
@Override
public Timer timer() {
return timer;
}
@Override
public TimerTask task() {
return task;
}
@Override
public boolean cancel() {
// only update the state it will be removed from HashedWheelBucket on next tick.
if (!compareAndSetState(ST_INIT, ST_CANCELLED)) {
return false;
}
// If a task should be canceled we put this to another queue which will be processed on each tick.
// So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way
// we can make again use of our MpscLinkedQueue and so minimize the locking / overhead as much as possible.
timer.cancelledTimeouts.add(this);
return true;
}
void remove() {
HashedWheelBucket bucket = this.bucket;
if (bucket != null) {
bucket.remove(this);
} else {
timer.pendingTimeouts.decrementAndGet();
}
}
public boolean compareAndSetState(int expected, int state) {
return STATE_UPDATER.compareAndSet(this, expected, state);
}
public int state() {
return state;
}
@Override
public boolean isCancelled() {
return state() == ST_CANCELLED;
}
@Override
public boolean isExpired() {
return state() == ST_EXPIRED;
}
public void expire() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final long currentTime = System.nanoTime();
long remaining = deadline - currentTime + timer.startTime;
StringBuilder buf = new StringBuilder(192)
.append("HashedWheelTimer")
.append('(')
.append("deadline: ");
if (remaining > 0) {
buf.append(remaining)
.append(" ns later");
} else if (remaining < 0) {
buf.append(-remaining)
.append(" ns ago");
} else {
buf.append("now");
}
if (isCancelled()) {
buf.append(", cancelled");
}
return buf.append(", task: ")
.append(task())
.append(')')
.toString();
}
}
|
if (!compareAndSetState(ST_INIT, ST_EXPIRED)) {
return;
}
try {
task.run(this);
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t);
}
}
| 1,022
| 100
| 1,122
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/TimerDispatcher.java
|
TimerDispatcher
|
goOffline
|
class TimerDispatcher implements TimerDispatch, DisposableBean {
/**
* time round schedule
*/
private final Timer wheelTimer;
/**
* Existing periodic scheduled tasks
*/
private final Map<Long, Timeout> currentCyclicTaskMap;
/**
* Existing temporary scheduled tasks
*/
private final Map<Long, Timeout> currentTempTaskMap;
/**
* One-time task response listener holds
* jobId - listener
*/
private final Map<Long, CollectResponseEventListener> eventListeners;
/**
* is dispatcher online running
*/
private final AtomicBoolean started;
public TimerDispatcher() {
this.wheelTimer = new HashedWheelTimer(r -> {
Thread ret = new Thread(r, "wheelTimer");
ret.setDaemon(true);
return ret;
}, 1, TimeUnit.SECONDS, 512);
this.currentCyclicTaskMap = new ConcurrentHashMap<>(8);
this.currentTempTaskMap = new ConcurrentHashMap<>(8);
this.eventListeners = new ConcurrentHashMap<>(8);
this.started = new AtomicBoolean(true);
}
@Override
public void addJob(Job addJob, CollectResponseEventListener eventListener) {
if (!this.started.get()) {
log.warn("Collector is offline, can not dispatch collect jobs.");
return;
}
WheelTimerTask timerJob = new WheelTimerTask(addJob);
if (addJob.isCyclic()) {
Timeout timeout = wheelTimer.newTimeout(timerJob, addJob.getInterval(), TimeUnit.SECONDS);
currentCyclicTaskMap.put(addJob.getId(), timeout);
} else {
Timeout timeout = wheelTimer.newTimeout(timerJob, 0, TimeUnit.SECONDS);
currentTempTaskMap.put(addJob.getId(), timeout);
eventListeners.put(addJob.getId(), eventListener);
}
}
@Override
public void cyclicJob(WheelTimerTask timerTask, long interval, TimeUnit timeUnit) {
if (!this.started.get()) {
log.warn("Collector is offline, can not dispatch collect jobs.");
return;
}
Long jobId = timerTask.getJob().getId();
// whether is the job has been canceled
if (currentCyclicTaskMap.containsKey(jobId)) {
Timeout timeout = wheelTimer.newTimeout(timerTask, interval, TimeUnit.SECONDS);
currentCyclicTaskMap.put(timerTask.getJob().getId(), timeout);
}
}
@Override
public void deleteJob(long jobId, boolean isCyclic) {
if (isCyclic) {
Timeout timeout = currentCyclicTaskMap.remove(jobId);
if (timeout != null) {
timeout.cancel();
}
} else {
Timeout timeout = currentTempTaskMap.remove(jobId);
if (timeout != null) {
timeout.cancel();
}
}
}
@Override
public void goOnline() {
currentCyclicTaskMap.forEach((key, value) -> value.cancel());
currentCyclicTaskMap.clear();
currentTempTaskMap.forEach((key, value) -> value.cancel());
currentTempTaskMap.clear();
started.set(true);
}
@Override
public void goOffline() {<FILL_FUNCTION_BODY>}
@Override
public void responseSyncJobData(long jobId, List<CollectRep.MetricsData> metricsDataTemps) {
currentTempTaskMap.remove(jobId);
CollectResponseEventListener eventListener = eventListeners.remove(jobId);
if (eventListener != null) {
eventListener.response(metricsDataTemps);
}
}
@Override
public void destroy() throws Exception {
this.wheelTimer.stop();
}
}
|
started.set(false);
currentCyclicTaskMap.forEach((key, value) -> value.cancel());
currentCyclicTaskMap.clear();
currentTempTaskMap.forEach((key, value) -> value.cancel());
currentTempTaskMap.clear();
| 1,029
| 71
| 1,100
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/WheelTimerTask.java
|
WheelTimerTask
|
initJobMetrics
|
class WheelTimerTask implements TimerTask {
private final Job job;
private final MetricsTaskDispatch metricsTaskDispatch;
private static final Gson GSON = new Gson();
public WheelTimerTask(Job job) {
this.metricsTaskDispatch = SpringContextHolder.getBean(MetricsTaskDispatch.class);
this.job = job;
// The initialization job will monitor the actual parameter value and replace the collection field
initJobMetrics(job);
}
/**
* Initialize job fill information
* @param job job
*/
private void initJobMetrics(Job job) {<FILL_FUNCTION_BODY>}
@Override
public void run(Timeout timeout) throws Exception {
job.setDispatchTime(System.currentTimeMillis());
metricsTaskDispatch.dispatchMetricsTask(timeout);
}
public Job getJob() {
return job;
}
}
|
List<Configmap> config = job.getConfigmap();
Map<String, Configmap> configmap = config.stream()
.peek(item -> {
// decode password
if (item.getType() == CommonConstants.PARAM_TYPE_PASSWORD && item.getValue() != null) {
String decodeValue = AesUtil.aesDecode(String.valueOf(item.getValue()));
if (decodeValue == null) {
log.error("Aes Decode value {} error.", item.getValue());
}
item.setValue(decodeValue);
} else if (item.getValue() != null && item.getValue() instanceof String) {
item.setValue(((String) item.getValue()).trim());
}
})
.collect(Collectors.toMap(Configmap::getKey, item -> item, (key1, key2) -> key1));
List<Metrics> metrics = job.getMetrics();
List<Metrics> metricsTmp = new ArrayList<>(metrics.size());
for (Metrics metric : metrics) {
JsonElement jsonElement = GSON.toJsonTree(metric);
CollectUtil.replaceSmilingPlaceholder(jsonElement, configmap);
metric = GSON.fromJson(jsonElement, Metrics.class);
if (job.getApp().equals(DispatchConstants.PROTOCOL_PUSH)) {
CollectUtil.replaceFieldsForPushStyleMonitor(metric, configmap);
}
metricsTmp.add(metric);
}
job.setMetrics(metricsTmp);
| 235
| 386
| 621
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/unit/impl/DataSizeConvert.java
|
DataSizeConvert
|
convert
|
class DataSizeConvert implements UnitConvert {
@Override
public String convert(String value, String originUnit, String newUnit) {<FILL_FUNCTION_BODY>}
@Override
public boolean checkUnit(String unit) {
if (unit == null || "".equals(unit)) {
return false;
}
for (DataUnit dataUnit : DataUnit.values()) {
// 不区分大小写
if (dataUnit.getUnit().equals(unit.toUpperCase())) {
return true;
}
}
return false;
}
}
|
if (value == null || "".equals(value)) {
return null;
}
BigDecimal size = new BigDecimal(value);
// 思路:value通过originUnit转换为字节,在转换为newUnit单位对应的值
for (DataUnit dataUnit : DataUnit.values()) {
if (dataUnit.getUnit().equals(originUnit.toUpperCase())) {
size = size.multiply(new BigDecimal(dataUnit.getScale()));
}
if (dataUnit.getUnit().equals(newUnit.toUpperCase())) {
size = size.divide(new BigDecimal(dataUnit.getScale()), 12, RoundingMode.HALF_UP);
}
}
return size.setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
| 148
| 220
| 368
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/unit/impl/TimeLengthConvert.java
|
TimeLengthConvert
|
convert
|
class TimeLengthConvert implements UnitConvert {
@Override
public String convert(String value, String originUnit, String newUnit) {<FILL_FUNCTION_BODY>}
@Override
public boolean checkUnit(String unit) {
if (unit == null || "".equals(unit)) {
return false;
}
for (TimeLengthUnit timeUnit : TimeLengthUnit.values()) {
// 不区分大小写
if (timeUnit.getUnit().equals(unit.toUpperCase())) {
return true;
}
}
return false;
}
}
|
if (value == null || "".equals(value)) {
return null;
}
BigDecimal length = new BigDecimal(value);
// 思路:value通过originUnit转换为纳秒,在转换为newUnit单位对应的值
for (TimeLengthUnit timeLengthUnit : TimeLengthUnit.values()) {
if (timeLengthUnit.getUnit().equals(originUnit.toUpperCase())) {
length = length.multiply(new BigDecimal(timeLengthUnit.getScale()));
}
if (timeLengthUnit.getUnit().equals(newUnit.toUpperCase())) {
length = length.divide(new BigDecimal(timeLengthUnit.getScale()), 12, RoundingMode.HALF_UP);
}
}
return length.setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
| 151
| 227
| 378
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/util/JsonPathParser.java
|
JsonPathParser
|
parseContentWithJsonPath
|
class JsonPathParser {
private static final ParseContext PARSER;
static {
Configuration conf = Configuration.defaultConfiguration()
.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
.addOptions(Option.ALWAYS_RETURN_LIST);
CacheProvider.setCache(new LRUCache(128));
PARSER = JsonPath.using(conf);
}
/**
* use json path to parse content
* @param content json content
* @param jsonPath jsonPath
* @return content [{'name': 'tom', 'speed': '433'},{'name': 'lili', 'speed': '543'}]
*/
public static List<Object> parseContentWithJsonPath(String content, String jsonPath) {
if (StringUtils.isAnyEmpty(content, jsonPath)) {
return Collections.emptyList();
}
return PARSER.parse(content).read(jsonPath);
}
/**
* use json path to parse content
* @param content json content
* @param jsonPath jsonPath
* @return content [{'name': 'tom', 'speed': '433'},{'name': 'lili', 'speed': '543'}]
*/
public static <T> T parseContentWithJsonPath(String content, String jsonPath, TypeRef<T> typeRef) {<FILL_FUNCTION_BODY>}
}
|
if (StringUtils.isAnyEmpty(content, jsonPath)) {
return null;
}
return PARSER.parse(content).read(jsonPath, typeRef);
| 359
| 46
| 405
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/collector/src/main/java/org/apache/hertzbeat/collector/util/PrivateKeyUtils.java
|
PrivateKeyUtils
|
writePrivateKey
|
class PrivateKeyUtils {
private static final String KEY_PATH = System.getProperty("user.home") + "/.ssh";
/**
* write private key to ~/.ssh, filename is ~/.ssh/id_rsa_${host}
* @param host host
* @param keyStr key string
* @return key file path
* @throws IOException if ~/.ssh is not exist and create dir error
*/
public static String writePrivateKey(String host, String keyStr) throws IOException {<FILL_FUNCTION_BODY>}
}
|
var sshPath = Paths.get(KEY_PATH);
if (!Files.exists(sshPath)) {
Files.createDirectories(sshPath);
}
var keyPath = Paths.get(KEY_PATH, "id_rsa_" + host);
if (!Files.exists(keyPath)) {
Files.writeString(keyPath, keyStr);
} else {
var oldKey = Files.readString(keyPath);
if (!Objects.equals(oldKey, keyStr)) {
Files.writeString(keyPath, keyStr);
}
}
return keyPath.toString();
| 140
| 154
| 294
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/config/AviatorConfiguration.java
|
AviatorConfiguration
|
configAviatorEvaluator
|
class AviatorConfiguration {
private static final int AVIATOR_LRU_CACHE_SIZE = 1024;
@Bean
public AviatorEvaluatorInstance configAviatorEvaluator() {<FILL_FUNCTION_BODY>}
/**
* Define a custom aviator string equality function
*/
private static class StrEqualFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
if (arg1 == null || arg2 == null) {
return AviatorBoolean.FALSE;
}
Object leftTmp = arg1.getValue(env);
Object rightTmp = arg2.getValue(env);
if (leftTmp == null || rightTmp == null) {
return AviatorBoolean.FALSE;
}
String left = String.valueOf(leftTmp);
String right = String.valueOf(rightTmp);
return AviatorBoolean.valueOf(left.equalsIgnoreCase(right));
}
@Override
public String getName() {
return "equals";
}
}
/**
* Custom aviator determines whether string 1 contains string 2 (case-insensitive)
*/
private static class StrContainsFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
if (arg1 == null || arg2 == null) {
return AviatorBoolean.FALSE;
}
Object leftTmp = arg1.getValue(env);
Object rightTmp = arg2.getValue(env);
if (leftTmp == null || rightTmp == null) {
return AviatorBoolean.FALSE;
}
String left = String.valueOf(leftTmp);
String right = String.valueOf(rightTmp);
return AviatorBoolean.valueOf(StringUtils.containsIgnoreCase(left, right));
}
@Override
public String getName() {
return "contains";
}
}
/**
* Custom aviator determines if a value exists for this object in the environment
*/
private static class ObjectExistsFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg) {
if (arg == null) {
return AviatorBoolean.FALSE;
}
Object keyTmp = arg.getValue(env);
if (Objects.isNull(keyTmp)) {
return AviatorBoolean.FALSE;
} else {
String key = String.valueOf(keyTmp);
return AviatorBoolean.valueOf(StringUtils.isNotEmpty(key));
}
}
@Override
public String getName() {
return "exists";
}
}
/**
* Custom aviator determines if a string matches a regex
* - regex You need to add "" or ''
*/
private static class StrMatchesFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
if (arg1 == null || arg2 == null) {
return AviatorBoolean.FALSE;
}
Object strTmp = arg1.getValue(env);
Object regexTmp = arg2.getValue(env);
if (strTmp == null || regexTmp == null) {
return AviatorBoolean.FALSE;
}
String str = String.valueOf(strTmp);
String regex = String.valueOf(regexTmp);
boolean isMatch = Pattern.compile(regex).matcher(str).matches();
return AviatorBoolean.valueOf(isMatch);
}
@Override
public String getName() {
return "matches";
}
}
}
|
AviatorEvaluatorInstance instance = AviatorEvaluator.getInstance();
// Configure AviatorEvaluator to cache compiled expressions using LRU
instance
.useLRUExpressionCache(AVIATOR_LRU_CACHE_SIZE)
.addFunction(new StrEqualFunction());
// limit loop Limit the number of loops
instance.setOption(Options.MAX_LOOP_COUNT, 10);
// Enables a partial Aviator syntax feature collection
instance.setOption(Options.FEATURE_SET,
Feature.asSet(Feature.If,
Feature.Assignment,
Feature.Let,
Feature.StringInterpolation));
// Configure the custom aviator function
instance.addOpFunction(OperatorType.BIT_OR, new AbstractFunction() {
@Override
public AviatorObject call(final Map<String, Object> env, final AviatorObject arg1,
final AviatorObject arg2) {
try {
Object value1 = arg1.getValue(env);
Object value2 = arg2.getValue(env);
Object currentValue = value1 == null ? value2 : value1;
if (arg1.getAviatorType() == AviatorType.String) {
return new AviatorString(String.valueOf(currentValue));
} else {
return AviatorDouble.valueOf(currentValue);
}
} catch (Exception e) {
log.error(e.getMessage());
}
return arg1.bitOr(arg2, env);
}
@Override
public String getName() {
return OperatorType.BIT_OR.getToken();
}
});
instance.addFunction(new StrContainsFunction());
instance.addFunction(new ObjectExistsFunction());
instance.addFunction(new StrMatchesFunction());
return instance;
| 997
| 470
| 1,467
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertDefine.java
|
AlertDefine
|
equals
|
class AlertDefine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Schema(title = "Threshold Id", example = "87584674384", accessMode = READ_ONLY)
private Long id;
@Schema(title = "Monitoring Type", example = "linux", accessMode = READ_WRITE)
@Length(max = 100)
@NotNull
private String app;
@Schema(title = "Monitoring Metrics", example = "cpu", accessMode = READ_WRITE)
@Length(max = 100)
@NotNull
private String metric;
@Schema(title = "Monitoring Metrics Field", example = "usage", accessMode = READ_WRITE)
@Length(max = 100)
private String field;
@Schema(title = "Is Apply All Default", example = "false", accessMode = READ_WRITE)
private boolean preset;
@Schema(title = "Alarm Threshold Expr", example = "usage>90", accessMode = READ_WRITE)
@Length(max = 2048)
@Column(length = 2048)
private String expr;
@Schema(title = "Alarm Level 0:High-Emergency-Critical Alarm 1:Medium-Critical-Critical Alarm 2:Low-Warning-Warning",
example = "1", accessMode = READ_WRITE)
@Min(0)
@Max(2)
private byte priority;
@Schema(title = "Alarm Trigger Times.The alarm is triggered only after the required number of times is reached",
example = "3", accessMode = READ_WRITE)
@Min(0)
@Max(10)
private Integer times;
@Schema(description = "Tags(status:success,env:prod)", example = "{name: key1, value: value1}",
accessMode = READ_WRITE)
@Convert(converter = JsonTagListAttributeConverter.class)
@Column(length = 2048)
private List<TagItem> tags;
@Schema(title = "Is Enable", example = "true", accessMode = READ_WRITE)
private boolean enable = true;
@Schema(title = "Is Send Alarm Recover Notice", example = "false", accessMode = READ_WRITE)
@Column(columnDefinition = "boolean default false")
private boolean recoverNotice = false;
@Schema(title = "Alarm Template", example = "linux {monitor_name}: {monitor_id} cpu usage high",
accessMode = READ_WRITE)
@Length(max = 2048)
@Column(length = 2048)
private String template;
@Schema(title = "The creator of this record", example = "tom", accessMode = READ_ONLY)
@CreatedBy
private String creator;
@Schema(title = "The modifier of this record", example = "tom", accessMode = READ_ONLY)
@LastModifiedBy
private String modifier;
@Schema(title = "Record create time", example = "1612198922000", accessMode = READ_ONLY)
@CreatedDate
private LocalDateTime gmtCreate;
@Schema(title = "Record modify time", example = "1612198444000", accessMode = READ_ONLY)
@LastModifiedDate
private LocalDateTime gmtUpdate;
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hashCode(app, metric, field, expr, priority, times, template);
}
}
|
if (this == o) {
return true;
}
if (!(o instanceof AlertDefine)) {
return false;
}
AlertDefine that = (AlertDefine) o;
return priority == that.priority && Objects.equal(app, that.app) && Objects.equal(metric, that.metric)
&& Objects.equal(field, that.field) && Objects.equal(expr, that.expr)
&& Objects.equal(times, that.times) && Objects.equal(template, that.template);
| 953
| 142
| 1,095
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/JsonMapAttributeConverter.java
|
JsonMapAttributeConverter
|
convertToEntityAttribute
|
class JsonMapAttributeConverter implements AttributeConverter<Map<String, String>, String> {
@Override
public String convertToDatabaseColumn(Map<String, String> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public Map<String, String> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<Map<String, String>> typeReference = new TypeReference<>() {};
return JsonUtil.fromJson(dbData, typeReference);
| 96
| 38
| 134
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/dto/PromVectorOrMatrix.java
|
MetricJsonObjectDeserializer
|
deserialize
|
class MetricJsonObjectDeserializer extends JsonDeserializer<JsonObject>{
@Override
public JsonObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>}
}
|
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
JsonObject metric = new JsonObject();
node.fields().forEachRemaining(entry -> metric.addProperty(entry.getKey(), entry.getValue().asText()));
return metric;
| 63
| 78
| 141
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/job/Job.java
|
Job
|
constructPriorMetrics
|
class Job {
/**
* Task Job id
*/
private long id;
/**
* Tenant id
*/
private long tenantId = 0;
/**
* Monitoring Task ID
*/
private long monitorId;
/**
* Is hide this app in main menus layout, only for app type, default true.
*/
private boolean hide = true;
/**
* Large categories of monitoring
* service-application service monitoring db-database
* monitoring custom-custom monitoring os-operating system monitoring...
*/
private String category;
/**
* Type of monitoring eg: linux | mysql | jvm
*/
private String app;
/**
* The internationalized name of the monitoring type
* PING CONNECT
*/
private Map<String, String> name;
/**
* The description and help of the monitoring type
* PING CONNECT - You can use the IP address or
* domain address of the peer service to monitor the PING connectivity between the local network and the peer network.
*/
private Map<String, String> help;
/**
* The monitor help link
*/
private Map<String, String> helpLink;
/**
* Task dispatch start timestamp
*/
private long timestamp;
/**
* Task collection time interval (unit: second) eg: 30,60,600
*/
private long interval = 600L;
/**
* Whether it is a recurring periodic task true is yes, false is no
*/
private boolean isCyclic = false;
/**
* monitor input need params
*/
private List<ParamDefine> params;
/**
* Metrics configuration eg: cpu memory
* eg: cpu memory
*/
private List<Metrics> metrics;
/**
* Monitoring configuration parameter properties and values eg: username password timeout host
*/
private List<Configmap> configmap;
/**
* the collect data response metrics as env configmap for other collect use. ^o^xxx^o^
*/
@JsonIgnore
private Map<String, Configmap> envConfigmaps;
/**
* collector use - timestamp when the task was scheduled by the time wheel
*/
@JsonIgnore
private transient long dispatchTime;
/**
* collector usage - metric group task execution priority view
* 0 - availability
* 1 - cpu | memory
* 2 - health
* 3 - otherMetrics
* ....
* 126 - otherMetrics
* 127 - lastPriorMetrics
*/
@JsonIgnore
private transient LinkedList<Set<Metrics>> priorMetrics;
/**
* collector use - Temporarily store one-time task metrics response data
*/
@JsonIgnore
private transient List<CollectRep.MetricsData> responseDataTemp;
/**
* collector use - construct to initialize metrics execution view
*/
public synchronized void constructPriorMetrics() {<FILL_FUNCTION_BODY>}
/**
* collector use - to get the next set of priority metric group tasks
*
* @param metrics Current Metrics
* @param first Is it the first time to get
* @return Metrics Tasks
* Returning null means: the job has been completed, and the collection of all metrics has ended
* Returning the empty set metrics that there are still metrics collection tasks at the current
* level that have not been completed,and the next level metrics task collection cannot be performed.
* The set returned empty means that there are still indicator collection tasks unfinished at the current level,
* and the task collection at the next level cannot be carried out
* Returns a set of data representation: get the next set of priority index collcet tasks
*/
public synchronized Set<Metrics> getNextCollectMetrics(Metrics metrics, boolean first) {
if (priorMetrics == null || priorMetrics.isEmpty()) {
return null;
}
Set<Metrics> metricsSet = priorMetrics.peek();
if (first) {
if (metricsSet.isEmpty()) {
log.error("metrics must has one [availability] metrics at least.");
}
return metricsSet;
}
if (metrics == null) {
log.error("metrics can not null when not first get");
return null;
}
if (!metricsSet.remove(metrics)) {
log.warn("Job {} appId {} app {} metrics {} remove empty error in priorMetrics.",
id, monitorId, app, metrics.getName());
}
if (metricsSet.isEmpty()) {
priorMetrics.poll();
if (priorMetrics.isEmpty()) {
return null;
}
Set<Metrics> source = priorMetrics.peek();
return new HashSet<>(source);
} else {
return Collections.emptySet();
}
}
public void addCollectMetricsData(CollectRep.MetricsData metricsData) {
if (responseDataTemp == null) {
responseDataTemp = new LinkedList<>();
}
responseDataTemp.add(metricsData);
}
public Map<String, Configmap> getEnvConfigmaps() {
return envConfigmaps;
}
public void addEnvConfigmaps(Map<String, Configmap> envConfigmaps) {
if (this.envConfigmaps == null) {
this.envConfigmaps = envConfigmaps;
} else {
this.envConfigmaps.putAll(envConfigmaps);
}
}
@Override
public Job clone() {
// deep clone
return JsonUtil.fromJson(JsonUtil.toJson(this), getClass());
}
}
|
Map<Byte, List<Metrics>> map = metrics.stream()
.peek(metric -> {
// Determine whether to configure aliasFields If not, configure the default
if ((metric.getAliasFields() == null || metric.getAliasFields().isEmpty()) && metric.getFields() != null) {
metric.setAliasFields(metric.getFields().stream().map(Metrics.Field::getField).collect(Collectors.toList()));
}
// Set the default metrics execution priority, if not filled, the default last priority
if (metric.getPriority() == null) {
metric.setPriority(Byte.MAX_VALUE);
}
})
.collect(Collectors.groupingBy(Metrics::getPriority));
// Construct a linked list of task execution order of the metrics
priorMetrics = new LinkedList<>();
map.values().forEach(metric -> {
Set<Metrics> metricsSet = Collections.synchronizedSet(new HashSet<>(metric));
priorMetrics.add(metricsSet);
});
priorMetrics.sort(Comparator.comparing(e -> {
Optional<Metrics> metric = e.stream().findAny();
if (metric.isPresent()) {
return metric.get().getPriority();
} else {
return Byte.MAX_VALUE;
}
}));
envConfigmaps = new HashMap<>(8);
| 1,412
| 343
| 1,755
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/job/Metrics.java
|
Metrics
|
consumeSubTaskResponse
|
class Metrics {
/**
* public property-name eg: cpu | memory | health
*/
private String name;
/**
* metrics name's i18n value
* zh-CN: CPU信息
* en-US: CPU Info
*/
private Map<String, String> i18n;
/**
* collect protocol eg: sql, ssh, http, telnet, wmi, snmp, sdk
*/
private String protocol;
/**
* Range (0-127) metrics scheduling priority, the smaller the value, the higher the priority
* The collection task of the next priority metrics will be scheduled only after the scheduled collection with the higher priority is completed.
* The default priority of the availability metrics is 0, and the range of other common metrics is 1-127, that is,
* the subsequent metrics tasks will only be scheduled after the availability is collected successfully.
*/
private Byte priority;
/**
* Is it visible true or false
* if false, web ui will not see this metrics.
*/
private boolean visible = true;
/**
* Public attribute - collection and monitoring final result attribute set eg: speed | times | size
*/
private List<Field> fields;
/**
* Public attribute - collection and monitoring pre-query attribute set eg: size1 | size2 | speedSize
*/
private List<String> aliasFields;
/**
* Public attribute - expression calculation, map the pre-query attribute (pre Fields)
* with the final attribute (fields), and calculate the final attribute (fields) value
* eg: size = size1 + size2, speed = speedSize
* <a href="https://www.yuque.com/boyan-avfmj/aviatorscript/ban32m">www.yuque.com/boyan-avfmj/aviatorscript/ban32m</a>
*/
private List<String> calculates;
/**
* unit conversion expr
* eg:
* - heap_used=B->MB
* - heap_total=B->MB
* - disk_free=B->GB
* - disk_total=B->GB
*/
private List<String> units;
/**
* Monitoring configuration information using the http protocol
*/
private HttpProtocol http;
/**
* Monitoring configuration information for ping using the icmp protocol
*/
private IcmpProtocol icmp;
/**
* Monitoring configuration information using the telnet protocol
*/
private TelnetProtocol telnet;
/**
* Monitoring configuration information using the public smtp protocol
*/
private SmtpProtocol smtp;
/**
* Monitoring configuration information using the public ntp protocol
*/
private NtpProtocol ntp;
/**
* Monitoring configuration information using the websocket protocol
*/
private WebsocketProtocol websocket;
/**
* Monitoring configuration information using the memcached protocol
*/
private MemcachedProtocol memcached;
/**
* Monitoring configuration information using the nebulaGraph protocol
*/
private NebulaGraphProtocol nebulaGraph;
/**
* Use udp implemented by socket for service port detection configuration information
*/
private UdpProtocol udp;
/**
* Database configuration information implemented using the public jdbc specification
*/
private JdbcProtocol jdbc;
/**
* Monitoring configuration information using the public ssh protocol
*/
private SshProtocol ssh;
/**
* Monitoring configuration information using the public redis protocol
*/
private RedisProtocol redis;
/**
* Monitoring configuration information using the public mongodb protocol
*/
private MongodbProtocol mongodb;
/**
* Get monitoring configuration information using public JMX protocol
*/
private JmxProtocol jmx;
/**
* Monitoring configuration information using the public snmp protocol
*/
private SnmpProtocol snmp;
/**
* Monitoring configuration information using the public ftp protocol
*/
private FtpProtocol ftp;
/**
* Monitoring configuration information using the public rocketmq protocol
*/
private RocketmqProtocol rocketmq;
/**
* Monitoring configuration information using push style
*/
private PushProtocol push;
/**
* Monitoring configuration information using the public prometheus protocol
*/
private PrometheusProtocol prometheus;
/**
* Monitoring configuration information using the public DNS protocol
*/
private DnsProtocol dns;
/**
* Monitoring configuration information using the public Nginx protocol
*/
private NginxProtocol nginx;
/**
* Monitoring configuration information using the public Nginx protocol
*/
private Pop3Protocol pop3;
/**
* Monitoring configuration information using the public http_sd protocol
*/
private HttpsdProtocol httpsd;
/**
* collector use - Temporarily store subTask metrics response data
*/
@JsonIgnore
private transient AtomicReference<CollectRep.MetricsData> subTaskDataRef;
/**
* collector use - Temporarily store subTask running num
*/
@JsonIgnore
private transient AtomicInteger subTaskNum;
/**
* collector use - Temporarily store subTask id
*/
@JsonIgnore
private transient Integer subTaskId;
/**
* is has subTask
*
* @return true - has
*/
public boolean isHasSubTask() {
return subTaskNum != null;
}
/**
* consume subTask
*
* @param metricsData response data
* @return is last task?
*/
public boolean consumeSubTaskResponse(CollectRep.MetricsData metricsData) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Metrics metrics = (Metrics) o;
return name.equals(metrics.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
/**
* Metrics.Field
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static class Field {
/**
* Metric name
*/
private String field;
/**
* metric field name's i18n value
* CPU Version
*/
private Map<String, String> i18n;
/**
* Metric type 0-number: number 1-string: string
*/
private byte type = 1;
/**
* Whether this field is the instance
*/
private boolean instance = false;
/**
* Whether this field is the label
*/
private boolean label = false;
/**
* Metric unit
*/
private String unit;
}
}
|
if (subTaskNum == null) {
return true;
}
synchronized (subTaskNum) {
int index = subTaskNum.decrementAndGet();
if (subTaskDataRef.get() == null) {
subTaskDataRef.set(metricsData);
} else {
if (metricsData.getValuesCount() >= 1) {
CollectRep.MetricsData.Builder dataBuilder = CollectRep.MetricsData.newBuilder(subTaskDataRef.get());
for (CollectRep.ValueRow valueRow : metricsData.getValuesList()) {
if (valueRow.getColumnsCount() == dataBuilder.getFieldsCount()) {
dataBuilder.addValues(valueRow);
} else {
log.error("consume subTask data value not mapping filed");
}
}
subTaskDataRef.set(dataBuilder.build());
}
}
return index == 0;
}
| 1,753
| 232
| 1,985
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonByteListAttributeConverter.java
|
JsonByteListAttributeConverter
|
convertToEntityAttribute
|
class JsonByteListAttributeConverter implements AttributeConverter<List<Byte>, String> {
@Override
public String convertToDatabaseColumn(List<Byte> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public List<Byte> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<Byte>> typeReference = new TypeReference<>() {};
return JsonUtil.fromJson(dbData, typeReference);
| 91
| 36
| 127
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonLongListAttributeConverter.java
|
JsonLongListAttributeConverter
|
convertToEntityAttribute
|
class JsonLongListAttributeConverter implements AttributeConverter<List<Long>, String> {
@Override
public String convertToDatabaseColumn(List<Long> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public List<Long> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<Long>> typeReference = new TypeReference<>() {};
List<Long> longList = JsonUtil.fromJson(dbData, typeReference);
if (longList == null && !dbData.isEmpty()) {
if (StringUtils.isNumeric(dbData)){
return List.of(Long.parseLong(dbData));
}
else throw new NumberFormatException("String convert to Long error");
}else return longList;
| 91
| 113
| 204
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonOptionListAttributeConverter.java
|
JsonOptionListAttributeConverter
|
convertToEntityAttribute
|
class JsonOptionListAttributeConverter implements AttributeConverter<List<ParamDefine.Option>, String> {
@Override
public String convertToDatabaseColumn(List<ParamDefine.Option> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public List<ParamDefine.Option> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<ParamDefine.Option>> typeReference = new TypeReference<>() {};
return JsonUtil.fromJson(dbData, typeReference);
| 103
| 40
| 143
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonStringListAttributeConverter.java
|
JsonStringListAttributeConverter
|
convertToEntityAttribute
|
class JsonStringListAttributeConverter implements AttributeConverter<List<String>, String> {
@Override
public String convertToDatabaseColumn(List<String> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public List<String> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<String>> typeReference = new TypeReference<>() {};
List<String> stringList = JsonUtil.fromJson(dbData, typeReference);
if (stringList == null && !dbData.isEmpty()) {
return List.of(dbData);
}else return stringList;
| 91
| 76
| 167
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonTagAttributeConverter.java
|
JsonTagAttributeConverter
|
convertToEntityAttribute
|
class JsonTagAttributeConverter implements AttributeConverter<TagItem, String> {
@Override
public String convertToDatabaseColumn(TagItem attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public TagItem convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<TagItem> typeReference = new TypeReference<>() {};
return JsonUtil.fromJson(dbData, typeReference);
| 84
| 35
| 119
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonTagListAttributeConverter.java
|
JsonTagListAttributeConverter
|
convertToEntityAttribute
|
class JsonTagListAttributeConverter implements AttributeConverter<List<TagItem>, String> {
@Override
public String convertToDatabaseColumn(List<TagItem> attribute) {
return JsonUtil.toJson(attribute);
}
@Override
public List<TagItem> convertToEntityAttribute(String dbData) {<FILL_FUNCTION_BODY>}
}
|
TypeReference<List<TagItem>> typeReference = new TypeReference<>() {};
List<TagItem> tagItems = JsonUtil.fromJson(dbData, typeReference);
if (tagItems == null) {
TypeReference<Map<String, String>> mapTypeReference = new TypeReference<>() {};
Map<String, String> map = JsonUtil.fromJson(dbData, mapTypeReference);
if (map != null) {
return map.entrySet().stream().map(entry -> new TagItem(entry.getKey(), entry.getValue())).collect(Collectors.toList());
} else {
return null;
}
} else {
return tagItems;
}
| 94
| 173
| 267
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/entity/manager/Tag.java
|
Tag
|
hashCode
|
class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Schema(title = "Tag Primary key index ID", example = "87584674384", accessMode = READ_ONLY)
private Long id;
@Schema(title = "Tag Field", example = "app", accessMode = READ_WRITE)
@NotNull
private String name;
@Schema(title = "Tag Value", example = "23", accessMode = READ_WRITE)
@Column(name = "`value`", length = 2048)
private String value;
@Schema(title = "Tag Color", example = "#ffff", accessMode = READ_WRITE)
private String color;
@Schema(title = "Tag Color", example = "Used for monitoring mysql", accessMode = READ_WRITE)
private String description;
@Schema(title = "Tag type 0: Auto-generated monitor (monitorId,monitorName) 1: user-generated 2: system preset",
accessMode = READ_WRITE)
@Min(0)
@Max(3)
private byte type;
@Schema(title = "The creator of this record", example = "tom", accessMode = READ_ONLY)
@CreatedBy
private String creator;
@Schema(title = "The modifier of this record", example = "tom", accessMode = READ_ONLY)
@LastModifiedBy
private String modifier;
@Schema(title = "Record create time", example = "1612198922000", accessMode = READ_ONLY)
@CreatedDate
private LocalDateTime gmtCreate;
@Schema(title = "Record modify time", example = "1612198444000", accessMode = READ_ONLY)
@LastModifiedDate
private LocalDateTime gmtUpdate;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(name, tag.name) && Objects.equals(value, tag.value);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int hash = 7;
hash = 13 * hash + (name == null ? 0 : name.hashCode()) + (value == null ? 0 : value.hashCode());
return hash;
| 602
| 51
| 653
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/queue/impl/InMemoryCommonDataQueue.java
|
InMemoryCommonDataQueue
|
getQueueSizeMetricsInfo
|
class InMemoryCommonDataQueue implements CommonDataQueue, DisposableBean {
private final LinkedBlockingQueue<Alert> alertDataQueue;
private final LinkedBlockingQueue<CollectRep.MetricsData> metricsDataToAlertQueue;
private final LinkedBlockingQueue<CollectRep.MetricsData> metricsDataToPersistentStorageQueue;
private final LinkedBlockingQueue<CollectRep.MetricsData> metricsDataToRealTimeStorageQueue;
public InMemoryCommonDataQueue() {
alertDataQueue = new LinkedBlockingQueue<>();
metricsDataToAlertQueue = new LinkedBlockingQueue<>();
metricsDataToPersistentStorageQueue = new LinkedBlockingQueue<>();
metricsDataToRealTimeStorageQueue = new LinkedBlockingQueue<>();
}
public Map<String, Integer> getQueueSizeMetricsInfo() {<FILL_FUNCTION_BODY>}
@Override
public void sendAlertsData(Alert alert) {
alertDataQueue.offer(alert);
}
@Override
public Alert pollAlertsData() throws InterruptedException {
return alertDataQueue.poll(2, TimeUnit.SECONDS);
}
@Override
public CollectRep.MetricsData pollMetricsDataToAlerter() throws InterruptedException {
return metricsDataToAlertQueue.poll(2, TimeUnit.SECONDS);
}
@Override
public CollectRep.MetricsData pollMetricsDataToPersistentStorage() throws InterruptedException {
return metricsDataToPersistentStorageQueue.poll(2, TimeUnit.SECONDS);
}
@Override
public CollectRep.MetricsData pollMetricsDataToRealTimeStorage() throws InterruptedException {
return metricsDataToRealTimeStorageQueue.poll(2, TimeUnit.SECONDS);
}
@Override
public void sendMetricsData(CollectRep.MetricsData metricsData) {
metricsDataToAlertQueue.offer(metricsData);
metricsDataToPersistentStorageQueue.offer(metricsData);
metricsDataToRealTimeStorageQueue.offer(metricsData);
}
@Override
public void destroy() {
alertDataQueue.clear();
metricsDataToAlertQueue.clear();
metricsDataToPersistentStorageQueue.clear();
metricsDataToRealTimeStorageQueue.clear();
}
}
|
Map<String, Integer> metrics = new HashMap<>(8);
metrics.put("alertDataQueue", alertDataQueue.size());
metrics.put("metricsDataToAlertQueue", metricsDataToAlertQueue.size());
metrics.put("metricsDataToPersistentStorageQueue", metricsDataToPersistentStorageQueue.size());
metrics.put("metricsDataToMemoryStorageQueue", metricsDataToRealTimeStorageQueue.size());
return metrics;
| 573
| 113
| 686
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/serialize/AlertSerializer.java
|
AlertSerializer
|
serialize
|
class AlertSerializer implements Serializer<Alert> {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
Serializer.super.configure(configs, isKey);
}
@Override
public byte[] serialize(String s, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte[] serialize(String topic, Headers headers, Alert data) {
return Serializer.super.serialize(topic, headers, data);
}
@Override
public void close() {
Serializer.super.close();
}
}
|
if (alert == null){
return null;
}
return JsonUtil.toJson(alert).getBytes();
| 160
| 33
| 193
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/serialize/KafkaMetricsDataDeserializer.java
|
KafkaMetricsDataDeserializer
|
deserialize
|
class KafkaMetricsDataDeserializer implements Deserializer<CollectRep.MetricsData> {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
Deserializer.super.configure(configs, isKey);
}
@Override
public CollectRep.MetricsData deserialize(String s, byte[] bytes){<FILL_FUNCTION_BODY>}
@Override
public CollectRep.MetricsData deserialize(String topic, Headers headers, byte[] data) {
return Deserializer.super.deserialize(topic, headers, data);
}
@Override
public void close() {
Deserializer.super.close();
}
}
|
try {
return CollectRep.MetricsData.parseFrom(bytes);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
| 180
| 45
| 225
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/service/AliYunSmsClient.java
|
AliYunSmsClient
|
sendMessage
|
class AliYunSmsClient {
private static final String RESPONSE_OK = "OK";
private static final String REGION = "ap-guangzhou";
private SmsClient smsClient;
private String appId;
private String signName;
private String templateId;
private String secretId;
private String secretKey;
public AliYunSmsClient(CommonProperties properties) {
if (properties == null || properties.getSms() == null || properties.getSms().getTencent() == null) {
log.error("init error, please config TencentSmsClient props in application.yml");
throw new IllegalArgumentException("please config TencentSmsClient props");
}
initSmsClient(properties.getSms().getAliYun());
}
private void initSmsClient(CommonProperties.AliYunSmsProperties tencent) {
this.appId = tencent.getAppId();
this.signName = tencent.getSignName();
this.templateId = tencent.getTemplateId();
this.secretId = tencent.getSecretId();
this.secretKey = tencent.getSecretKey();
Credential cred = new Credential(tencent.getSecretId(), tencent.getSecretKey());
smsClient = new SmsClient(cred, REGION);
}
/**
* Alibaba cloud sends SMS messages
* @param appId appId
* @param signName sign name
* @param templateId template id
* @param templateValues template values
* @param phones phones num
*/
public void sendMessage(String appId, String signName, String templateId, String secretId, String secretKey,
String[] templateValues, String[] phones){<FILL_FUNCTION_BODY>}
/**
* Send a text message
* @param templateValues template values
* @param phones phones num
*/
public void sendMessage(String[] templateValues, String[] phones) {
sendMessage(this.appId, this.signName, this.templateId, this.secretId, this.secretKey, templateValues, phones);
}
}
|
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
SendSmsRequest req = new SendSmsRequest();
req.setSmsSdkAppId(appId);
req.setSignName(signName);
req.setTemplateId(templateId);
req.setTemplateParamSet(templateValues);
req.setPhoneNumberSet(phones);
try {
Map<String, Object> param = new HashMap<>();
// taskName: monitoring name, alert: alarm level, message: alarm content, sysTime:system time
param.put("taskName", templateValues[0]);
param.put("alert", templateValues[1]);
param.put("message", templateValues[2]);
param.put("sysTime", dateTime.format(formatter));
SendSmsResponse smsResponse = AliYunSendSmsUtil.send(param, signName, templateId, phones[0], secretId, secretKey);
String code = smsResponse.body.code;
if (!RESPONSE_OK.equals(code)) {
throw new SendMessageException(code + ":" + smsResponse.body.message);
}
} catch (Exception e) {
log.warn(e.getMessage());
throw new SendMessageException(e.getMessage());
}
| 553
| 344
| 897
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/service/TencentSmsClient.java
|
TencentSmsClient
|
initSmsClient
|
class TencentSmsClient {
private static final String RESPONSE_OK = "Ok";
private static final String REGION = "ap-guangzhou";
private SmsClient smsClient;
private String appId;
private String signName;
private String templateId;
public TencentSmsClient(CommonProperties properties) {
if (properties == null || properties.getSms() == null || properties.getSms().getTencent() == null) {
log.error("init error, please config TencentSmsClient props in application.yml");
throw new IllegalArgumentException("please config TencentSmsClient props");
}
initSmsClient(properties.getSms().getTencent());
}
private void initSmsClient(CommonProperties.TencentSmsProperties tencent) {<FILL_FUNCTION_BODY>}
/**
* send text message
* @param appId appId
* @param signName sign name
* @param templateId template id
* @param templateValues template values
* @param phones phones num
*/
public void sendMessage(String appId, String signName, String templateId,
String[] templateValues, String[] phones) {
SendSmsRequest req = new SendSmsRequest();
req.setSmsSdkAppId(appId);
req.setSignName(signName);
req.setTemplateId(templateId);
req.setTemplateParamSet(templateValues);
req.setPhoneNumberSet(phones);
try {
SendSmsResponse smsResponse = this.smsClient.SendSms(req);
SendStatus sendStatus = smsResponse.getSendStatusSet()[0];
if (!RESPONSE_OK.equals(sendStatus.getCode())) {
throw new SendMessageException(sendStatus.getCode() + ":" + sendStatus.getMessage());
}
} catch (Exception e) {
log.warn(e.getMessage());
throw new SendMessageException(e.getMessage());
}
}
/**
* send text message
* @param templateValues template values
* @param phones phones num
*/
public void sendMessage(String[] templateValues, String[] phones) {
sendMessage(this.appId, this.signName, this.templateId, templateValues, phones);
}
}
|
this.appId = tencent.getAppId();
this.signName = tencent.getSignName();
this.templateId = tencent.getTemplateId();
Credential cred = new Credential(tencent.getSecretId(), tencent.getSecretKey());
smsClient = new SmsClient(cred, REGION);
| 594
| 93
| 687
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/support/CommonThreadPool.java
|
CommonThreadPool
|
initWorkExecutor
|
class CommonThreadPool implements DisposableBean {
private ThreadPoolExecutor workerExecutor;
public CommonThreadPool() {
initWorkExecutor();
}
private void initWorkExecutor() {<FILL_FUNCTION_BODY>}
/**
* Run the task thread
* @param runnable Task
* @throws RejectedExecutionException when thread pool full
*/
public void execute(Runnable runnable) throws RejectedExecutionException {
workerExecutor.execute(runnable);
}
@Override
public void destroy() throws Exception {
if (workerExecutor != null) {
workerExecutor.shutdownNow();
}
}
}
|
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setUncaughtExceptionHandler((thread, throwable) -> {
log.error("common executor has uncaughtException.");
log.error(throwable.getMessage(), throwable);
})
.setDaemon(true)
.setNameFormat("common-worker-%d")
.build();
workerExecutor = new ThreadPoolExecutor(2,
Integer.MAX_VALUE,
10,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
| 174
| 151
| 325
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/support/ResourceBundleUtf8Control.java
|
ResourceBundleUtf8Control
|
newBundle
|
class ResourceBundleUtf8Control extends ResourceBundle.Control {
private static final String JAVA_CLASS = "java.class";
private static final String JAVA_PROPERTIES = "java.properties";
private static final String SPILT = "://";
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {<FILL_FUNCTION_BODY>}
private String toResourceName0(String bundleName, String suffix) {
// application protocol check
if (bundleName.contains(SPILT)) {
return null;
} else {
return toResourceName(bundleName, suffix);
}
}
}
|
String bundleName = toBundleName(baseName, locale);
ResourceBundle bundle = null;
if (JAVA_CLASS.equals(format)) {
try {
@SuppressWarnings("unchecked")
Class<? extends ResourceBundle> bundleClass
= (Class<? extends ResourceBundle>) loader.loadClass(bundleName);
// If the class isn't a ResourceBundle subclass, throw a
// ClassCastException.
if (ResourceBundle.class.isAssignableFrom(bundleClass)) {
bundle = bundleClass.newInstance();
} else {
throw new ClassCastException(bundleClass.getName()
+ " cannot be cast to ResourceBundle");
}
} catch (ClassNotFoundException ignored) {}
} else if (JAVA_PROPERTIES.equals(format)) {
final String resourceName = toResourceName0(bundleName, "properties");
if (resourceName == null) {
return null;
}
final ClassLoader classLoader = loader;
final boolean reloadFlag = reload;
InputStream stream;
try {
stream = AccessController.doPrivileged(
(PrivilegedExceptionAction<InputStream>) () -> {
InputStream is = null;
if (reloadFlag) {
URL url = classLoader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
// Disable caches to get fresh data for
// reloading.
connection.setUseCaches(false);
is = connection.getInputStream();
}
}
} else {
is = classLoader.getResourceAsStream(resourceName);
}
return is;
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getException();
}
if (stream != null) {
try {
bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
} finally {
stream.close();
}
}
} else {
throw new IllegalArgumentException("unknown format: " + format);
}
return bundle;
| 189
| 548
| 737
|
<methods>public List<java.util.Locale> getCandidateLocales(java.lang.String, java.util.Locale) ,public static final java.util.ResourceBundle.Control getControl(List<java.lang.String>) ,public java.util.Locale getFallbackLocale(java.lang.String, java.util.Locale) ,public List<java.lang.String> getFormats(java.lang.String) ,public static final java.util.ResourceBundle.Control getNoFallbackControl(List<java.lang.String>) ,public long getTimeToLive(java.lang.String, java.util.Locale) ,public boolean needsReload(java.lang.String, java.util.Locale, java.lang.String, java.lang.ClassLoader, java.util.ResourceBundle, long) ,public java.util.ResourceBundle newBundle(java.lang.String, java.util.Locale, java.lang.String, java.lang.ClassLoader, boolean) throws java.lang.IllegalAccessException, java.lang.InstantiationException, java.io.IOException,public java.lang.String toBundleName(java.lang.String, java.util.Locale) ,public final java.lang.String toResourceName(java.lang.String, java.lang.String) <variables>static final boolean $assertionsDisabled,private static final java.util.ResourceBundle.Control.CandidateListCache CANDIDATES_CACHE,public static final List<java.lang.String> FORMAT_CLASS,public static final List<java.lang.String> FORMAT_DEFAULT,public static final List<java.lang.String> FORMAT_PROPERTIES,private static final java.util.ResourceBundle.Control INSTANCE,public static final long TTL_DONT_CACHE,public static final long TTL_NO_EXPIRATION_CONTROL
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/support/SpringContextHolder.java
|
SpringContextHolder
|
isActive
|
class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private static ConfigurableApplicationContext configurableApplicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
set(applicationContext);
if (applicationContext instanceof ConfigurableApplicationContext) {
configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
}
}
private static void set(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> clazz) {
assertApplicationContext();
return (T) applicationContext.getBean(clazz);
}
public static void shutdown() {
assertApplicationContext();
configurableApplicationContext.close();
}
public static boolean isActive() {<FILL_FUNCTION_BODY>}
private static void assertApplicationContext() {
if (null == applicationContext || null == configurableApplicationContext) {
throw new RuntimeException("applicationContext is null, please inject the springContextHolder");
}
}
}
|
if (configurableApplicationContext == null) {
return false;
}
return configurableApplicationContext.isActive();
| 360
| 34
| 394
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/support/valid/HostParamValidator.java
|
HostParamValidator
|
isValid
|
class HostParamValidator implements ConstraintValidator<HostValid, String> {
public static final String HTTP = "http://";
public static final String HTTPS = "https://";
public static final String BLANK = "";
public static final String PATTERN_HTTP = "(?i)http://";
public static final String PATTERN_HTTPS = "(?i)https://";
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {<FILL_FUNCTION_BODY>}
}
|
if (value != null && value.toLowerCase().contains(HTTP)){
value = value.replaceAll(PATTERN_HTTP, BLANK);
}
if (value != null && value.toLowerCase().contains(HTTPS)){
value = value.replace(PATTERN_HTTPS, BLANK);
}
return IpDomainUtil.validateIpDomain(value);
| 131
| 103
| 234
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/AesUtil.java
|
AesUtil
|
aesEncode
|
class AesUtil {
/**
* Default encryption key The AES encryption key is 16 bits by default.
* If the AES encryption key is larger than or smaller than 16 bits, an error message is displayed
*/
private static final String ENCODE_RULES = "tomSun28HaHaHaHa";
/**
* Default algorithm
*/
private static final String ALGORITHM_STR = "AES/CBC/PKCS5Padding";
private static final String AES = "AES";
/**
* Encryption key The AES encryption key is 16 bits.
* If the AES encryption key is larger than 16 bits, an error message is displayed
*/
private static String secretKey = ENCODE_RULES;
private AesUtil() {}
public static void setDefaultSecretKey(String secretKeyNow) {
secretKey = secretKeyNow;
}
public static String aesEncode(String content) {
return aesEncode(content, secretKey);
}
public static String aesDecode(String content) {
return aesDecode(content, secretKey);
}
public static boolean isCiphertext(String text) {
return isCiphertext(text, secretKey);
}
/**
* Encrypted plaintext aes cbc mode
*
* @param content content
* @param encryptKey secretKey
* @return ciphertext
*/
public static String aesEncode(String content, String encryptKey) {<FILL_FUNCTION_BODY>}
/**
* Decrypt ciphertext
*
* @param content ciphertext
* @param decryptKey secretKey
* @return content
*/
public static String aesDecode(String content, String decryptKey) {
try {
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), AES);
// cipher based on the algorithm AES
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
// init cipher Encrypt_mode or Decrypt_mode operation, the second parameter is the KEY used
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(decryptKey.getBytes(StandardCharsets.UTF_8)));
// base64 decode content
byte[] bytesContent = Base64.getDecoder().decode(content);
// decode content to byte array
byte[] byteDecode = cipher.doFinal(bytesContent);
return new String(byteDecode, StandardCharsets.UTF_8);
} catch (BadPaddingException e) {
if (!ENCODE_RULES.equals(decryptKey)) {
log.warn("There has default encode secret encode content, try to decode with default secret key");
return aesDecode(content, ENCODE_RULES);
}
log.error("aes decode content error: {}, please config right common secret key", e.getMessage());
return content;
} catch (NoSuchAlgorithmException e) {
log.error("no such algorithm: {}", e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
log.error("illegal block size: {}", e.getMessage(), e);
} catch (NullPointerException e) {
log.error("null point exception: {}", e.getMessage(), e);
} catch (Exception e) {
log.error("aes decode error: {}", e.getMessage(), e);
}
return content;
}
/**
* Determine whether it is encrypted
* @param text text
* @return true-是 false-否
*/
public static boolean isCiphertext(String text, String decryptKey) {
// First use whether it is base64 to determine whether it has been encrypted
if (Base64Util.isBase64(text)) {
// If it is base64, decrypt directly to determine
try {
SecretKeySpec keySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(decryptKey.getBytes(StandardCharsets.UTF_8)));
byte[] bytesContent = Base64.getDecoder().decode(text);
byte[] byteDecode = cipher.doFinal(bytesContent);
return byteDecode != null;
} catch (Exception e) {
return false;
}
}
return false;
}
}
|
try {
// todo consider not init cipher every time and test performance
SecretKeySpec keySpec = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), AES);
// cipher based on the algorithm AES
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
// init cipher Encrypt_mode or Decrypt_mode operation, the second parameter is the KEY used
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(encryptKey.getBytes(StandardCharsets.UTF_8)));
// get content bytes, must utf-8
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
// encode content to byte array
byte[] byteAes = cipher.doFinal(byteEncode);
// base64 encode content
return new String(Base64.getEncoder().encode(byteAes), StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("aes encode content error: {}", e.getMessage(), e);
return content;
}
| 1,181
| 279
| 1,460
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/AliYunSendSmsUtil.java
|
AliYunSendSmsUtil
|
send
|
class AliYunSendSmsUtil {
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config();
config.accessKeyId = accessKeyId;
config.accessKeySecret = accessKeySecret;
return new com.aliyun.dysmsapi20170525.Client(config);
}
/**
* Method for sending SMS messages: Enter the map format
*/
public static SendSmsResponse send(Map<String, Object> map, String singName, String templateCode, String phone, String accessKeyId, String accessKeySecret) throws Exception {<FILL_FUNCTION_BODY>}
}
|
com.aliyun.dysmsapi20170525.Client client = AliYunSendSmsUtil.createClient(accessKeyId, accessKeySecret);
SendSmsRequest sendReq = new SendSmsRequest()
.setPhoneNumbers(phone)//The phone number that received the text message
.setSignName(singName)//SMS signature
.setTemplateCode(templateCode)//SMS Template Code
.setTemplateParam(new ObjectMapper().writeValueAsString(map)); //The actual value of the SMS template variable
SendSmsResponse sendResp = client.sendSms(sendReq);
return sendResp;
| 191
| 166
| 357
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/Base64Util.java
|
Base64Util
|
isBase64
|
class Base64Util {
public static boolean isBase64(String base64) {<FILL_FUNCTION_BODY>}
}
|
try {
return Base64.getDecoder().decode(base64) != null;
} catch (Exception e) {
return false;
}
| 38
| 45
| 83
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/CommonUtil.java
|
CommonUtil
|
getMessageFromThrowable
|
class CommonUtil {
private static final Pattern EMAIL_PATTERN = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
private static final Pattern PHONE_PATTERN = Pattern.compile("^(((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(19[0-9])|(18[0-9])|(17[0-9]))+\\d{8})?$");
private static final int PHONE_LENGTH = 11;
/**
* Converts the string str to the int numeric type
*
* @param str string
* @return double number
*/
public static Integer parseStrInteger(final String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
return Integer.parseInt(str);
} catch (Exception e) {
log.debug(e.getMessage(), e);
return null;
}
}
/**
* Converts the string str to the double number type
*
* @param str string
* @return double number
*/
public static Double parseStrDouble(final String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
return Double.parseDouble(str);
} catch (Exception e) {
log.debug(e.getMessage(), e);
return null;
}
}
/**
* Converts the time string str to seconds
*
* @param str string
* @return double number
*/
public static int parseTimeStrToSecond(final String str) {
if (StringUtils.isEmpty(str)) {
return -1;
}
try {
return LocalTime.parse(str).toSecondOfDay();
} catch (Exception e) {
log.debug(e.getMessage(), e);
return -1;
}
}
/**
* Converts the string str, which may contain units, to the double number type
* Limit numeric values to four decimal places
*
* @param str string
* @param unit STRING UNIT
* @return DOUBLE DIGITS IN STRING FORMAT Decimal point up to 4 places
*/
public static String parseDoubleStr(String str, String unit) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
if (unit != null && str.endsWith(unit)) {
str = str.substring(0, str.length() - unit.length());
}
BigDecimal bigDecimal = new BigDecimal(str);
return bigDecimal.setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
} catch (Exception e) {
log.debug(e.getMessage(), e);
return null;
}
}
/**
* Mailbox format check
*
* @param email email
* @return Is the verification successful
*/
public static boolean validateEmail(final String email) {
if (StringUtils.isBlank(email)) {
return false;
}
Matcher m = EMAIL_PATTERN.matcher(email);
return m.find();
}
/**
* Mobile phone format verification
*
* @param phoneNum mobilePhoneNumber
* @return Is the verification successful
*/
public static boolean validatePhoneNum(final String phoneNum) {
if (StringUtils.isBlank(phoneNum) || phoneNum.length() != PHONE_LENGTH) {
return false;
}
Matcher m = PHONE_PATTERN.matcher(phoneNum);
return m.find();
}
public static String getMessageFromThrowable(Throwable throwable) {<FILL_FUNCTION_BODY>}
public static String removeBlankLine(String value) {
if (value == null) {
return null;
}
return value.replaceAll("(?m)^\\s*$(\\n|\\r\\n)", "");
}
public static String getLangMappingValueFromI18nMap(String lang, Map<String, String> i18nMap) {
if (i18nMap == null || i18nMap.isEmpty()) {
return null;
}
return Optional.ofNullable(i18nMap.get(lang))
.orElse(i18nMap.values().stream()
.findFirst().orElse(null));
}
}
|
if (throwable == null) {
return "throwable is null, unknown error.";
}
String message = null;
Throwable cause = throwable.getCause();
if (cause != null) {
message = cause.getMessage();
}
if (message == null || "".equals(message)) {
message = throwable.getMessage();
}
if (message == null || "".equals(message)) {
message = throwable.getLocalizedMessage();
}
if (message == null || "".equals(message)) {
message = throwable.toString();
}
if (message == null || "".equals(message)) {
message = "unknown error.";
}
return message;
| 1,213
| 187
| 1,400
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/IntervalExpressionUtil.java
|
IntervalExpressionUtil
|
validNumberIntervalExpress
|
class IntervalExpressionUtil {
private static final String SPLIT_OR = "\\|\\|";
private static final String SPLIT_AND = ",";
private static final String SPLIT_EQU_LEFT = "(";
private static final String SPLIT_EQU_RIGHT = ")";
private static final String SPLIT_EQ_LEFT = "[";
private static final String SPLIT_EQ_RIGHT = "]";
private static final String NEGATIVE = "-∞";
private static final String POSITIVE = "+∞";
/**
* CHECK WHETHER THE VALUE IS IN AN INTERVAL RANGE
* @param numberValue NumericalValue
* @param expression INTERVAL EXPRESSION
* @return true-yes false-no
*/
public static boolean validNumberIntervalExpress(Double numberValue, String expression) {<FILL_FUNCTION_BODY>}
}
|
if (expression == null || "".equals(expression)) {
return true;
}
if (numberValue == null) {
return false;
}
try {
String[] expressions = expression.split(SPLIT_OR);
for (String expr : expressions) {
String[] values = expr.substring(1, expr.length() - 1).split(SPLIT_AND);
if (values.length != 2) {
continue;
}
Double[] doubleValues = new Double[2];
if (NEGATIVE.equals(values[0])) {
doubleValues[0] = Double.MIN_VALUE;
} else {
doubleValues[0] = Double.parseDouble(values[0]);
}
if (POSITIVE.equals(values[1])) {
doubleValues[1] = Double.MAX_VALUE;
} else {
doubleValues[1] = Double.parseDouble(values[1]);
}
String startBracket = expr.substring(0, 1);
String endBracket = expr.substring(expr.length() - 1);
if (SPLIT_EQU_LEFT.equals(startBracket)) {
if (SPLIT_EQU_RIGHT.equals(endBracket)) {
if (numberValue > doubleValues[0] && numberValue < doubleValues[1]) {
return true;
}
} else if (SPLIT_EQ_RIGHT.equals(endBracket)) {
if (numberValue > doubleValues[0] && numberValue <= doubleValues[1]) {
return true;
}
}
} else if (SPLIT_EQ_LEFT.equals(startBracket)) {
if (SPLIT_EQU_RIGHT.equals(endBracket)) {
if (numberValue >= doubleValues[0] && numberValue < doubleValues[1]) {
return true;
}
} else if (SPLIT_EQ_RIGHT.equals(endBracket)) {
if (numberValue >= doubleValues[0] && numberValue <= doubleValues[1]) {
return true;
}
}
}
}
return false;
} catch (Exception e) {
log.debug(e.getMessage(), e);
return false;
}
| 236
| 580
| 816
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/IpDomainUtil.java
|
IpDomainUtil
|
validateIpDomain
|
class IpDomainUtil {
private static final Pattern DOMAIN_PATTERN =
Pattern.compile("^[-\\w]+(\\.[-\\w]+)*$");
private static final String LOCALHOST = "localhost";
/**
* HTTP header schema
*/
private static final Pattern DOMAIN_SCHEMA = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://){1}[^\\s]*");
/**
* whether it is ip or domain
* @param ipDomain ip domain string
* @return true-yes false-no
*/
public static boolean validateIpDomain(String ipDomain) {<FILL_FUNCTION_BODY>}
/**
* if domain or ip has http / https schema
* @param domainIp host
* @return true or false
*/
public static boolean isHasSchema(String domainIp) {
if (domainIp == null || "".equals(domainIp)) {
return false;
}
return DOMAIN_SCHEMA.matcher(domainIp).matches();
}
/**
* get localhost IP
* @return ip
*/
public static String getLocalhostIp() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
if (!netInterface.isLoopback() && !netInterface.isVirtual() && netInterface.isUp()) {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
log.warn(e.getMessage());
}
return null;
}
/**
*
* @param ipDomain ip domain
* @return IP address type
*/
public static String checkIpAddressType(String ipDomain){
if (InetAddressUtils.isIPv6Address(ipDomain)) {
return CollectorConstants.IPV6;
}
return CollectorConstants.IPV4;
}
/**
* get current local host name
* @return hostname
*/
public static String getCurrentHostName() {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
return inetAddress.getHostName();
} catch (UnknownHostException e) {
return null;
}
}
}
|
if (ipDomain == null || "".equals(ipDomain)) {
return false;
}
ipDomain = ipDomain.trim();
if (LOCALHOST.equalsIgnoreCase(ipDomain)) {
return true;
}
if (InetAddressUtils.isIPv4Address(ipDomain)) {
return true;
}
if (InetAddressUtils.isIPv6Address(ipDomain)) {
return true;
}
return DOMAIN_PATTERN.matcher(ipDomain).matches();
| 704
| 136
| 840
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/JsonUtil.java
|
JsonUtil
|
fromJson
|
class JsonUtil {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.registerModule(new JavaTimeModule());
}
public static String toJson(Object source) {
if (source == null) {
return null;
}
try {
return OBJECT_MAPPER.writeValueAsString(source);
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
return null;
}
}
public static <T> T fromJson(String jsonStr, Class<T> clazz) {<FILL_FUNCTION_BODY>}
public static <T> T fromJson(String jsonStr, TypeReference<T> type) {
if (!StringUtils.hasText(jsonStr)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(jsonStr, type);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
public static JsonNode fromJson(String jsonStr) {
if (!StringUtils.hasText(jsonStr)) {
return null;
}
try {
return OBJECT_MAPPER.readTree(jsonStr);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
}
|
if (!StringUtils.hasText(jsonStr)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(jsonStr, clazz);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
| 414
| 77
| 491
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/ProtoJsonUtil.java
|
ProtoJsonUtil
|
toProtobuf
|
class ProtoJsonUtil {
private static final JsonFormat.Printer PRINTER = JsonFormat.printer();
private static final JsonFormat.Parser PARSER = JsonFormat.parser();
/**
* protobuf to json
* @param proto protobuf
* @return json
*/
public static String toJsonStr(Message proto) {
try {
return PRINTER.print(proto);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
/**
* json to protobuf
* @param json json str
* @param builder proto instance builder
* @return protobuf
*/
public static Message toProtobuf(String json, Message.Builder builder) {<FILL_FUNCTION_BODY>}
}
|
try {
PARSER.merge(json, builder);
return builder.build();
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
| 201
| 54
| 255
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/ResourceBundleUtil.java
|
ResourceBundleUtil
|
getBundle
|
class ResourceBundleUtil {
private static final ResourceBundleUtf8Control BUNDLE_UTF_8_CONTROL = new ResourceBundleUtf8Control();
private static final Integer LANG_REGION_LENGTH = 2;
static {
// set default locale by env
try {
String langEnv = System.getenv("LANG");
if (langEnv != null) {
String[] langArr = langEnv.split("\\.");
if (langArr.length >= 1) {
String[] regionArr = langArr[0].split("_");
if (regionArr.length == LANG_REGION_LENGTH) {
String language = regionArr[0];
String region = regionArr[1];
Locale locale = new Locale(language, region);
Locale.setDefault(locale);
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* get resource bundle by bundle name
* @param bundleName bundle name
* @return resource bundle
*/
public static ResourceBundle getBundle(String bundleName) {<FILL_FUNCTION_BODY>}
}
|
try {
return ResourceBundle.getBundle(bundleName, BUNDLE_UTF_8_CONTROL);
} catch (MissingResourceException resourceException) {
return ResourceBundle.getBundle(bundleName, Locale.US, BUNDLE_UTF_8_CONTROL);
}
| 306
| 75
| 381
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/SnowFlakeIdWorker.java
|
SnowFlakeIdWorker
|
nextId
|
class SnowFlakeIdWorker {
/**
* Start timestamp, in milliseconds; This is 2021-06-01
*/
private static final long TW_EPOCH = 1622476800000L;
/**
* The number of bits occupied by the machine ID
*/
private static final long WORKER_ID_BITS = 4L;
/**
* Maximum machine ID supported, 0-15
* <p>
* The source code of PS.Twitter is -1L ^ (-1L << workerIdBits); Here the final xor operation with -1,
* because of the particularity of -1's binary complement, it is equivalent to taking the inverse.
*/
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
/**
* The number of bits the sequence occupies in the ID
*/
private static final long SEQUENCE_BITS = 8L;
/**
* Number of machine ID shifts left
*/
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
/**
* Time truncated left shift number
*/
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
/**
* The maximum mask of the generated sequence, 256
*/
private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
/**
* Working machine ID(0~15)
*/
private final long workerId;
/**
* Millisecond sequence (0~256)
*/
private long sequence = 0L;
/**
* Timestamp of the last ID generated
*/
private long lastTimestamp = -1L;
/**
* How to create an ID generator: Use the serial number range of the working machine [0, 15]
*
* @param workerId Working machine ID
*/
public SnowFlakeIdWorker(long workerId) {
if (workerId < 0 || workerId > MAX_WORKER_ID) {
Random random = new Random(workerId);
workerId = random.nextInt((int) MAX_WORKER_ID);
log.warn("Worker ID can't be greater than {} or less than 0, use random: {}.", MAX_WORKER_ID, workerId);
}
this.workerId = workerId;
}
/**
* How to create an ID generator: Create the generator using the local IP as the machine ID
*/
public SnowFlakeIdWorker() {
int workerId = 0;
String host = IpDomainUtil.getLocalhostIp();
if (host == null) {
Random random = new Random(workerId);
workerId = random.nextInt((int) MAX_WORKER_ID);
} else {
workerId = host.hashCode() % (int) MAX_WORKER_ID;
workerId = Math.abs(workerId);
}
this.workerId = workerId;
}
/**
* get next id
* thread safe
* @return id with 15 length
*/
public synchronized long nextId() {<FILL_FUNCTION_BODY>}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
|
long timestamp = timeGen();
if (lastTimestamp == timestamp) {
// Generated at the same time, then the sequence number +1
sequence = (sequence + 1) & SEQUENCE_MASK;
// Sequence overflow in milliseconds: The maximum value is exceeded
if (sequence == 0) {
// Block to the next millisecond to get a new timestamp
timestamp = tilNextMillis(lastTimestamp);
}
} else {
// The timestamp changes and the sequence resets in milliseconds
sequence = 0L;
}
// Timestamp of the last ID generated
lastTimestamp = timestamp;
// Shift it and put it together with the OR operation
return ((timestamp - TW_EPOCH) << TIMESTAMP_LEFT_SHIFT)
| (workerId << WORKER_ID_SHIFT)
| sequence;
| 929
| 220
| 1,149
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/StrBuffer.java
|
StrBuffer
|
skipBlankTabs
|
class StrBuffer {
private static final String POSITIVE_INF = "+inf";
private static final String NEGATIVE_INF = "-inf";
private static final long POSITIVE_INF_VALUE = 0x7FF0000000000000L;
private static final long NEGATIVE_INF_VALUE = 0xFFF0000000000000L;
private final char[] chars;
private int left;
private int right;
public StrBuffer(String s) {
this.chars = s.toCharArray();
this.left = 0;
this.right = s.length() - 1;
}
/**
* Reading the current character, left++
*
* @return Current subscript character
*/
public char read() {
if (left > right) {
throw new IndexOutOfBoundsException("StrBuffer use charAt method error. left=" + left + ", right=" + right);
}
return chars[left++];
}
/**
* Rollback one character
*/
public void rollback() {
if (left > 0) {
left--;
}
}
/**
* Only the index character of left+i is queried; there is no left++ operation
*
* @param i index
* @return left+iThe character corresponding to the index
*/
public char charAt(int i) {
if (left + i > right) {
throw new IndexOutOfBoundsException("StrBuffer use charAt method error. left=" + left + ", i=" + i);
}
return chars[left + i];
}
/**
* Converting a string object
*
* @return charA string corresponding to an array
*/
public String toStr() {
StringBuilder builder = new StringBuilder();
for (int i = left; i <= right; i++) {
builder.append(chars[i]);
}
return builder.toString();
}
/**
* transition double
*
* @return char double integer corresponding to the array
*/
public double toDouble() {
String s = toStr();
return parseDouble(s);
}
/**
* transition long
*
* @return char the long integer corresponding to the array
*/
public long toLong() {
String s = toStr();
return parseLong(s);
}
public void skipBlankTabs() {<FILL_FUNCTION_BODY>}
private boolean isBlankOrTab(char c) {
return c == ' ' || c == '\t';
}
public boolean isEmpty() {
return left > right;
}
/**
* string -> long, We need to determine if it's INF
*
* @param s string
* @return long
*/
public static long parseLong(String s) {
if (POSITIVE_INF.equalsIgnoreCase(s)) {
return POSITIVE_INF_VALUE;
}
if (NEGATIVE_INF.equalsIgnoreCase(s)) {
return NEGATIVE_INF_VALUE;
}
return Double.valueOf(s).longValue();
}
/**
* string -> double, We need to determine if it's INF
*
* @param s string
* @return double
*/
public static double parseDouble(String s) {
if (POSITIVE_INF.equalsIgnoreCase(s)) {
return POSITIVE_INF_VALUE;
} else if (NEGATIVE_INF.equalsIgnoreCase(s)) {
return NEGATIVE_INF_VALUE;
}
return Double.parseDouble(s);
}
}
|
while (left <= right) {
if (this.isBlankOrTab(chars[left])) {
left++;
} else {
break;
}
}
while (right >= left) {
if (this.isBlankOrTab(chars[right])) {
right--;
} else {
break;
}
}
| 982
| 97
| 1,079
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/TimePeriodUtil.java
|
TimePeriodUtil
|
parseTokenTime
|
class TimePeriodUtil {
/**
* parse tokenTime to TemporalAmount
* @param tokenTime eg: "1m", "5M", "3D", "30m", "2h", "1Y", "3W"
* @return TemporalAmount
*/
public static TemporalAmount parseTokenTime(String tokenTime) {<FILL_FUNCTION_BODY>}
}
|
if (Character.isUpperCase(tokenTime.charAt(tokenTime.length() - 1))) {
return Period.parse("P" + tokenTime);
} else {
return Duration.parse("PT" + tokenTime);
}
| 102
| 65
| 167
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/common/src/main/java/org/apache/hertzbeat/common/util/prometheus/PrometheusUtil.java
|
PrometheusUtil
|
parseLabel
|
class PrometheusUtil {
//An unknown format occurred during parsing because parsing cannot continue
// or the end of the input stream has been reached
private static final int ERROR_FORMAT = -1;
//The input stream ends normally
private static final int NORMAL_END = -2;
private static final int COMMENT_LINE = -3;
private static int parseMetricName(InputStream inputStream, Metric.MetricBuilder metricBuilder) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
int i;
i = inputStream.read();
if (i == -1) {
return NORMAL_END;
}
else if (i == '#') {
return COMMENT_LINE;
}
while (i != -1) {
if (i == ' ' || i == '{') {
metricBuilder.metricName(stringBuilder.toString());
return i;
}
stringBuilder.append((char) i);
i = inputStream.read();
}
return ERROR_FORMAT;
}
private static int parseLabel(InputStream inputStream, List<Label> labelList) throws IOException {<FILL_FUNCTION_BODY>}
private static int parseLabelList(InputStream inputStream, Metric.MetricBuilder metricBuilder) throws IOException {
List<Label> labelList = new ArrayList<>();
int i;
i = parseLabel(inputStream, labelList);
while (i == ',') {
i = parseLabel(inputStream, labelList);
}
if (i == -1) {
return ERROR_FORMAT;
}
metricBuilder.labelList(labelList);
return i;
}
private static int parseValue(InputStream inputStream, Metric.MetricBuilder metricBuilder) throws IOException {
int i;
StringBuilder stringBuilder = new StringBuilder();
i = inputStream.read();
while (i != -1 && i != ' ' && i != '\n') {
stringBuilder.append((char) i);
i = inputStream.read();
}
String string = stringBuilder.toString();
switch (string) {
case "NaN":
metricBuilder.value(Double.NaN);
break;
case "+Inf":
metricBuilder.value(Double.POSITIVE_INFINITY);
break;
case "-Inf":
metricBuilder.value(Double.NEGATIVE_INFINITY);
break;
default:
try {
BigDecimal bigDecimal = new BigDecimal(string);
metricBuilder.value(bigDecimal.doubleValue());
} catch (NumberFormatException e) {
return ERROR_FORMAT;
}
break;
}
if (i == -1) {
return NORMAL_END;
}
else {
return i; // ' ' or \n'
}
}
private static int parseTimestamp(InputStream inputStream, Metric.MetricBuilder metricBuilder) throws IOException {
int i;
StringBuilder stringBuilder = new StringBuilder();
i = inputStream.read();
while (i != -1 && i != '\n') {
stringBuilder.append((char) i);
i = inputStream.read();
}
String string = stringBuilder.toString();
try {
metricBuilder.timestamp(Long.parseLong(string));
} catch (NumberFormatException e) {
return ERROR_FORMAT;
}
if (i == -1) {
return NORMAL_END;
}
else {
return i; // '\n'
}
}
// return value:
// -1: error format
// -2: normal end
// '\n': more lines
private static int parseMetric(InputStream inputStream, List<Metric> metrics) throws IOException {
Metric.MetricBuilder metricBuilder = new Metric.MetricBuilder();
int i = parseMetricName(inputStream, metricBuilder); // RET: -1, -2, -3, '{', ' '
if (i == ERROR_FORMAT || i == NORMAL_END || i == COMMENT_LINE) {
return i;
}
if (i == '{') {
i = parseLabelList(inputStream, metricBuilder); // RET: -1, '}'
if (i == ERROR_FORMAT) {
return i;
}
}
i = parseValue(inputStream, metricBuilder); // RET: -1, -2, '\n', ' '
if (i != ' ') {
metrics.add(metricBuilder.build());
return i;
}
i = parseTimestamp(inputStream, metricBuilder); // RET: -1, -2, '\n'
metrics.add(metricBuilder.build());
return i;
}
private static int skipCommentLine(InputStream inputStream) throws IOException {
int i = inputStream.read();
while (i != -1 && i != '\n') {
i = inputStream.read();
}
if (i == -1) {
return NORMAL_END;
}
return i;
}
public static List<Metric> parseMetrics(InputStream inputStream) throws IOException {
List<Metric> metricList= new ArrayList<>();
int i = parseMetric(inputStream, metricList);
while (i == '\n' || i == COMMENT_LINE) {
if (i == COMMENT_LINE) {
if (skipCommentLine(inputStream) == NORMAL_END) {
return metricList;
}
}
i = parseMetric(inputStream, metricList);
}
if (i == NORMAL_END) {
return metricList;
}
else {
return null;
}
}
}
|
Label.LabelBuilder labelBuilder = new Label.LabelBuilder();
int i;
StringBuilder labelName = new StringBuilder();
i = inputStream.read();
while (i != -1 && i != '=') {
labelName.append((char) i);
i = inputStream.read();
}
if (i == -1) {
return ERROR_FORMAT;
}
labelBuilder.name(labelName.toString());
if (inputStream.read() != '\"') {
return ERROR_FORMAT;
}
StringBuilder labelValue = new StringBuilder();
i = inputStream.read();
while (i != -1 && i != ',' && i != '}') {
labelValue.append((char) i);
i = inputStream.read();
}
if (i == -1 || labelValue.charAt(labelValue.length() - 1) != '\"') {
return ERROR_FORMAT;
}
// skip space only in this condition
if (i == '}' && inputStream.read() != ' ') {
return ERROR_FORMAT;
}
labelValue.deleteCharAt(labelValue.length() - 1);
labelBuilder.value(labelValue.toString());
labelList.add(labelBuilder.build());
return i;
| 1,476
| 338
| 1,814
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/DispatcherAlarm.java
|
DispatchTask
|
sendNotify
|
class DispatchTask implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Alert alert = dataQueue.pollAlertsData();
if (alert != null) {
// Determining alarm type storage 判断告警类型入库
alertStoreHandler.store(alert);
// 通知分发
sendNotify(alert);
}
} catch (IgnoreException ignored) {
} catch (InterruptedException e) {
log.error(e.getMessage());
} catch (Exception exception) {
log.error(exception.getMessage(), exception);
}
}
}
private void sendNotify(Alert alert) {<FILL_FUNCTION_BODY>}
}
|
List<NoticeRule> noticeRules = matchNoticeRulesByAlert(alert);
// todo Send notification here temporarily single thread 发送通知这里暂时单线程
if (noticeRules != null) {
for (NoticeRule rule : noticeRules) {
try {
if (rule.getTemplateId() == null) {
List<Long> receiverIdList = rule.getReceiverId();
for (Long receiverId : receiverIdList) {
sendNoticeMsg(getOneReceiverById(receiverId),
null, alert);
}
} else {
List<Long> receiverIdList = rule.getReceiverId();
for (Long receiverId : receiverIdList) {
sendNoticeMsg(getOneReceiverById(receiverId),
getOneTemplateById(rule.getTemplateId()), alert);
}
}
} catch (AlertNoticeException e) {
log.warn("DispatchTask sendNoticeMsg error, message: {}", e.getMessage());
}
}
}
| 199
| 259
| 458
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java
|
AbstractAlertNotifyHandlerImpl
|
renderContent
|
class AbstractAlertNotifyHandlerImpl implements AlertNotifyHandler {
private static final String NUMBER_FORMAT = "0";
protected static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
protected ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
@Resource
protected RestTemplate restTemplate;
@Resource
protected AlerterProperties alerterProperties;
@Resource
protected NoticeConfigService noticeConfigService;
protected String renderContent(NoticeTemplate noticeTemplate, Alert alert) throws TemplateException, IOException {<FILL_FUNCTION_BODY>}
@EventListener(SystemConfigChangeEvent.class)
public void onEvent(SystemConfigChangeEvent event) {
log.info("{} receive system config change event: {}.", this.getClass().getName(), event.getSource());
this.bundle = ResourceBundleUtil.getBundle("alerter");
}
}
|
StringTemplateLoader stringLoader = new StringTemplateLoader();
freemarker.template.Template templateRes;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
cfg.setNumberFormat(NUMBER_FORMAT);
Map<String, Object> model = new HashMap<>(16);
model.put("title", bundle.getString("alerter.notify.title"));
if (alert.getTags() != null) {
String monitorId = alert.getTags().get(CommonConstants.TAG_MONITOR_ID);
if (monitorId != null) {
model.put("monitorId", monitorId);
}
String monitorName = alert.getTags().get(CommonConstants.TAG_MONITOR_NAME);
if (monitorName != null) {
model.put("monitorName", monitorName);
}
String monitorHost = alert.getTags().get(CommonConstants.TAG_MONITOR_HOST);
if (monitorHost != null) {
model.put("monitorHost", monitorHost);
}
String thresholdId = alert.getTags().get(CommonConstants.TAG_THRESHOLD_ID);
if (thresholdId != null) {
model.put("thresholdId", thresholdId);
}
}
model.put("alarmId", alert.getId());
model.put("status", alert.getStatus());
model.put("monitorIdLabel", bundle.getString("alerter.notify.monitorId"));
model.put("monitorNameLabel", bundle.getString("alerter.notify.monitorName"));
model.put("monitorHostLabel", bundle.getString("alerter.notify.monitorHost"));
model.put("target", alert.getTarget());
model.put("targetLabel", bundle.getString("alerter.notify.target"));
model.put("priorityLabel", bundle.getString("alerter.notify.priority"));
model.put("priority", bundle.getString("alerter.priority." + alert.getPriority()));
model.put("priorityValue", alert.getPriority());
model.put("triggerTimeLabel", bundle.getString("alerter.notify.triggerTime"));
model.put("triggerTime", DTF.format(Instant.ofEpochMilli(alert.getLastAlarmTime()).atZone(ZoneId.systemDefault()).toLocalDateTime()));
if (CommonConstants.ALERT_STATUS_CODE_RESTORED == alert.getStatus()) {
model.put("restoreTimeLabel", bundle.getString("alerter.notify.restoreTime"));
model.put("restoreTime", DTF.format(Instant.ofEpochMilli(alert.getFirstAlarmTime()).atZone(ZoneId.systemDefault()).toLocalDateTime()));
}
model.put("timesLabel", bundle.getString("alerter.notify.times"));
model.put("times", alert.getTimes());
model.put("contentLabel", bundle.getString("alerter.notify.content"));
model.put("content", alert.getContent());
model.put("tagsLabel", bundle.getString("alerter.notify.tags"));
model.put("tags", alert.getTags());
if (noticeTemplate == null) {
noticeTemplate = noticeConfigService.getDefaultNoticeTemplateByType(type());
}
if (noticeTemplate == null) {
log.error("alert does not have mapping default notice template. type: {}.", type());
throw new NullPointerException(type() + " does not have mapping default notice template");
}
// TODO 单实例复用缓存 考虑多线程问题
String templateName = "freeMakerTemplate";
stringLoader.putTemplate(templateName, noticeTemplate.getContent());
cfg.setTemplateLoader(stringLoader);
templateRes = cfg.getTemplate(templateName, Locale.CHINESE);
String template = FreeMarkerTemplateUtils.processTemplateIntoString(templateRes, model);
return template.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1");
| 235
| 1,005
| 1,240
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AliYunAlertNotifyHandlerImpl.java
|
AliYunAlertNotifyHandlerImpl
|
send
|
class AliYunAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private final AliYunSmsClient aliYunSmsClient;
private final ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 0;
}
}
|
// SMS notification
try {
String monitorName = null;
if (alert.getTags() != null) {
monitorName = alert.getTags().get(CommonConstants.TAG_MONITOR_NAME);
}
String[] params = new String[3];
params[0] = monitorName == null ? alert.getTarget() : monitorName;
params[1] = bundle.getString("alerter.priority." + alert.getPriority());
params[2] = alert.getContent();
aliYunSmsClient.sendMessage(params, new String[]{receiver.getPhone()});
} catch (Exception e) {
throw new AlertNoticeException("[Sms Notify Error] " + e.getMessage());
}
| 119
| 187
| 306
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/DbAlertStoreHandlerImpl.java
|
DbAlertStoreHandlerImpl
|
store
|
class DbAlertStoreHandlerImpl implements AlertStoreHandler {
private final MonitorService monitorService;
private final AlertService alertService;
@Override
public void store(Alert alert) {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> tags = alert.getTags();
String monitorIdStr = tags != null ? tags.get(CommonConstants.TAG_MONITOR_ID) : null;
if (monitorIdStr != null) {
long monitorId = Long.parseLong(monitorIdStr);
Monitor monitor = monitorService.getMonitor(monitorId);
if (monitor == null) {
log.warn("Dispatch alarm the monitorId: {} not existed, ignored. target: {}.", monitorId, alert.getTarget());
return;
}
if (!tags.containsKey(CommonConstants.TAG_MONITOR_NAME)) {
tags.put(CommonConstants.TAG_MONITOR_NAME, monitor.getName());
}
if (!tags.containsKey(CommonConstants.TAG_MONITOR_HOST)) {
tags.put(CommonConstants.TAG_MONITOR_HOST, monitor.getHost());
}
if (monitor.getStatus() == CommonConstants.UN_MANAGE_CODE) {
// When monitoring is not monitored, ignore and silence its alarm messages
return;
}
if (CommonConstants.AVAILABILITY.equals(alert.getTarget())) {
if (alert.getStatus() == CommonConstants.ALERT_STATUS_CODE_PENDING && monitor.getStatus() == CommonConstants.AVAILABLE_CODE) {
// Availability Alarm Need to change the monitoring status to unavailable
// 可用性告警 需变更任务状态为不可用
monitorService.updateMonitorStatus(monitor.getId(), CommonConstants.UN_AVAILABLE_CODE);
} else if (alert.getStatus() == CommonConstants.ALERT_STATUS_CODE_RESTORED && monitor.getStatus() == CommonConstants.UN_AVAILABLE_CODE) {
// If the alarm is restored, the monitoring state needs to be restored
// 若是恢复告警 需对任务状态进行恢复
monitorService.updateMonitorStatus(monitorId, CommonConstants.AVAILABLE_CODE);
}
}
} else {
log.debug("store extern alert content: {}.", alert);
}
if (tags != null && tags.containsKey(CommonConstants.IGNORE)) {
throw new IgnoreException("Ignore this alarm.");
}
// Alarm store db
alertService.addAlert(alert);
| 66
| 579
| 645
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/DingTalkRobotAlertNotifyHandlerImpl.java
|
DingTalkRobotAlertNotifyHandlerImpl
|
send
|
class DingTalkRobotAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 5;
}
/**
* 钉钉机器人请求消息体
*
*
* @version 1.0
*/
@Data
private static class DingTalkWebHookDto {
private static final String MARKDOWN = "markdown";
/**
* 消息类型
*/
private String msgtype = MARKDOWN;
/**
* markdown消息
*/
private MarkdownDTO markdown;
}
@Data
private static class MarkdownDTO {
/**
* 消息内容
*/
private String text;
/**
* 消息标题
*/
private String title;
}
}
|
try {
DingTalkWebHookDto dingTalkWebHookDto = new DingTalkWebHookDto();
MarkdownDTO markdownDTO = new MarkdownDTO();
markdownDTO.setText(renderContent(noticeTemplate, alert));
markdownDTO.setTitle(bundle.getString("alerter.notify.title"));
dingTalkWebHookDto.setMarkdown(markdownDTO);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<DingTalkWebHookDto> httpEntity = new HttpEntity<>(dingTalkWebHookDto, headers);
String webHookUrl = alerterProperties.getDingTalkWebhookUrl() + receiver.getAccessToken();
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
assert responseEntity.getBody() != null;
if (responseEntity.getBody().getErrCode() == 0) {
log.debug("Send dingTalk webHook: {} Success", webHookUrl);
} else {
log.warn("Send dingTalk webHook: {} Failed: {}", webHookUrl, responseEntity.getBody().getErrMsg());
throw new AlertNoticeException(responseEntity.getBody().getErrMsg());
}
} else {
log.warn("Send dingTalk webHook: {} Failed: {}", webHookUrl, responseEntity.getBody());
throw new AlertNoticeException("Http StatusCode " + responseEntity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[DingTalk Notify Error] " + e.getMessage());
}
| 259
| 466
| 725
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/DiscordBotAlertNotifyHandlerImpl.java
|
DiscordBotAlertNotifyHandlerImpl
|
send
|
class DiscordBotAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 9;
}
@Data
@Builder
private static class DiscordNotifyDTO {
private List<EmbedDTO> embeds;
}
@Data
@Builder
private static class EmbedDTO {
private String title;
private String description;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
private static class DiscordResponseDTO {
private String id;
private Integer type;
private String content;
private String message;
private Integer code;
}
}
|
try {
var notifyBody = DiscordNotifyDTO.builder()
.embeds(List.of(EmbedDTO.builder()
.title("[" + bundle.getString("alerter.notify.title") + "]")
.description(renderContent(noticeTemplate, alert))
.build()))
.build();
var url = String.format(alerterProperties.getDiscordWebhookUrl(), receiver.getDiscordChannelId());
var headers = new HttpHeaders();
headers.add("Authorization", "Bot " + receiver.getDiscordBotToken());
headers.setContentType(MediaType.APPLICATION_JSON);
var request = new HttpEntity<>(notifyBody, headers);
var entity = restTemplate.postForEntity(url, request, DiscordResponseDTO.class);
if (entity.getStatusCode() == HttpStatus.OK && entity.getBody() != null) {
var body = entity.getBody();
if (body.id != null) {
log.debug("Send Discord Bot Success");
} else {
log.warn("Send Discord Bot Failed: {}, error_code: {}", body.code, body.message);
throw new AlertNoticeException(body.message);
}
} else {
log.warn("Send Discord Bot Failed {}", entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[Discord Bot Notify Error] " + e.getMessage());
}
| 220
| 391
| 611
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/EmailAlertNotifyHandlerImpl.java
|
EmailAlertNotifyHandlerImpl
|
send
|
class EmailAlertNotifyHandlerImpl implements AlertNotifyHandler {
private final JavaMailSender javaMailSender;
private final MailService mailService;
@Value("${spring.mail.host:smtp.demo.com}")
private String host;
@Value("${spring.mail.username:demo}")
private String username;
@Value("${spring.mail.password:demo}")
private String password;
@Value("${spring.mail.port:465}")
private Integer port;
@Value("${spring.mail.properties.mail.smtp.ssl.enable:true}")
private boolean sslEnable = true;
private final GeneralConfigDao generalConfigDao;
private final ObjectMapper objectMapper;
private static final String TYPE = "email";
private ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 1;
}
@EventListener(SystemConfigChangeEvent.class)
public void onEvent(SystemConfigChangeEvent event) {
log.info("{} receive system config change event: {}.", this.getClass().getName(), event.getSource());
this.bundle = ResourceBundleUtil.getBundle("alerter");
}
}
|
try {
//获取sender
JavaMailSenderImpl sender = (JavaMailSenderImpl) javaMailSender;
String fromUsername = username;
try {
boolean useDatabase = false;
GeneralConfig emailConfig = generalConfigDao.findByType(TYPE);
if (emailConfig != null && emailConfig.getContent() != null) {
// 若启用数据库配置
String content = emailConfig.getContent();
EmailNoticeSender emailNoticeSenderConfig = objectMapper.readValue(content, EmailNoticeSender.class);
if (emailNoticeSenderConfig.isEnable()) {
sender.setHost(emailNoticeSenderConfig.getEmailHost());
sender.setPort(emailNoticeSenderConfig.getEmailPort());
sender.setUsername(emailNoticeSenderConfig.getEmailUsername());
sender.setPassword(emailNoticeSenderConfig.getEmailPassword());
Properties props = sender.getJavaMailProperties();
props.put("mail.smtp.ssl.enable", emailNoticeSenderConfig.isEmailSsl());
fromUsername = emailNoticeSenderConfig.getEmailUsername();
useDatabase = true;
}
}
if (!useDatabase) {
// 若数据库未配置则启用yml配置
sender.setHost(host);
sender.setPort(port);
sender.setUsername(username);
sender.setPassword(password);
Properties props = sender.getJavaMailProperties();
props.put("mail.smtp.ssl.enable", sslEnable);
}
} catch (Exception e) {
log.error("Type not found {}", e.getMessage());
}
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setSubject(bundle.getString("alerter.notify.title"));
//Set sender Email 设置发件人Email
messageHelper.setFrom(fromUsername);
//Set recipient Email 设定收件人Email
messageHelper.setTo(receiver.getEmail());
messageHelper.setSentDate(new Date());
//Build email templates 构建邮件模版
String process = mailService.buildAlertHtmlTemplate(alert, noticeTemplate);
//Set Email Content Template 设置邮件内容模版
messageHelper.setText(process, true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
throw new AlertNoticeException("[Email Notify Error] " + e.getMessage());
}
| 373
| 645
| 1,018
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/FlyBookAlertNotifyHandlerImpl.java
|
FlyBookAlertNotifyHandlerImpl
|
send
|
class FlyBookAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 6;
}
@Data
private static class FlyBookWebHookDto {
private static final String MARKDOWN = "post";
/**
* 消息类型
*/
@JsonProperty("msg_type")
private String msgType = MARKDOWN;
private Content content;
}
/**
* 消息内容
*/
@Data
private static class Content {
public Post post;
}
@Data
private static class FlyBookContent {
/**
* 格式 目前支持文本、超链接、@人的功能 text a at
*/
public String tag;
/**
* 文本
*/
public String text;
/**
* 超链接地址
*/
public String href;
@JsonProperty("user_id")
public String userId;
@JsonProperty("user_name")
public String userName;
}
@Data
private static class Post {
@JsonProperty("zh_cn")
public ZhCn zhCn;
}
@Data
private static class ZhCn {
/**
* 标题
*/
public String title;
/**
* 内容
*/
public List<List<FlyBookContent>> content;
}
}
|
try {
FlyBookWebHookDto flyBookWebHookDto = new FlyBookWebHookDto();
Content content = new Content();
Post post = new Post();
ZhCn zhCn = new ZhCn();
content.setPost(post);
post.setZhCn(zhCn);
flyBookWebHookDto.setMsgType("post");
List<List<FlyBookContent>> contents = new ArrayList<>();
List<FlyBookContent> contents1 = new ArrayList<>();
FlyBookContent flyBookContent = new FlyBookContent();
flyBookContent.setTag("text");
flyBookContent.setText(renderContent(noticeTemplate, alert));
contents1.add(flyBookContent);
FlyBookContent bookContent = new FlyBookContent();
bookContent.setTag("a");
bookContent.setText(bundle.getString("alerter.notify.console"));
bookContent.setHref(alerterProperties.getConsoleUrl());
contents1.add(bookContent);
contents.add(contents1);
zhCn.setTitle("[" + bundle.getString("alerter.notify.title") + "]");
zhCn.setContent(contents);
flyBookWebHookDto.setContent(content);
String webHookUrl = alerterProperties.getFlyBookWebhookUrl() + receiver.getWechatId();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<FlyBookWebHookDto> flyEntity = new HttpEntity<>(flyBookWebHookDto, headers);
ResponseEntity<CommonRobotNotifyResp> entity = restTemplate.postForEntity(webHookUrl,
flyEntity, CommonRobotNotifyResp.class);
if (entity.getStatusCode() == HttpStatus.OK) {
assert entity.getBody() != null;
if (entity.getBody().getCode() == null || entity.getBody().getCode() == 0) {
log.debug("Send feiShu webHook: {} Success", webHookUrl);
} else {
log.warn("Send feiShu webHook: {} Failed: {}", webHookUrl, entity.getBody().getMsg());
throw new AlertNoticeException(entity.getBody().getMsg());
}
} else {
log.warn("Send feiShu webHook: {} Failed: {}", webHookUrl, entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[FeiShu Notify Error] " + e.getMessage());
}
| 419
| 672
| 1,091
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/GotifyAlertNotifyHandlerImpl.java
|
GotifyAlertNotifyHandlerImpl
|
send
|
class GotifyAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl{
/**
* 发送报警通知
*
* @param receiver Notification configuration information 通知配置信息
* @param noticeTemplate Notification configuration information 通知配置信息
* @param alert Alarm information 告警信息
* @throws AlertNoticeException when send receiver error
*/
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
/**
* 通知类型
*
* @return 通知类型
*/
@Override
public byte type() {
return 13;
}
@Data
private static class GotifyWebHookDto {
private String title;
private String message;
private Extras extras;
@Data
public static class Extras {
@JsonProperty("client::display")
private ClientDisplay clientDisplay;
}
@Data
public static class ClientDisplay {
private String contentType;
}
}
}
|
try {
GotifyWebHookDto gotifyWebHookDto = new GotifyWebHookDto();
gotifyWebHookDto.setTitle(bundle.getString("alerter.notify.title"));
gotifyWebHookDto.setMessage(renderContent(noticeTemplate, alert));
GotifyWebHookDto.ClientDisplay clientDisplay = new GotifyWebHookDto.ClientDisplay();
clientDisplay.setContentType("text/markdown");
GotifyWebHookDto.Extras extras = new GotifyWebHookDto.Extras();
extras.setClientDisplay(clientDisplay);
gotifyWebHookDto.setExtras(extras);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<GotifyWebHookDto> httpEntity = new HttpEntity<>(gotifyWebHookDto, headers);
String webHookUrl = String.format(alerterProperties.getGotifyWebhookUrl(), receiver.getGotifyToken());
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
log.debug("Send Gotify webHook: {} Success", webHookUrl);
} else {
log.warn("Send Gotify webHook: {} Failed: {}", webHookUrl, responseEntity.getBody());
throw new AlertNoticeException("Http StatusCode " + responseEntity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[Gotify Notify Error] " + e.getMessage());
}
| 287
| 426
| 713
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/HuaweiCloudSmnAlertNotifyHandlerImpl.java
|
HuaweiCloudSmnAlertNotifyHandlerImpl
|
getSmnClient
|
class HuaweiCloudSmnAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private final ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
private final Map<String, SmnClient> smnClientMap = new ConcurrentHashMap<>();
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {
try {
var smnClient = getSmnClient(receiver);
var request = new PublishMessageRequest()
.withTopicUrn(receiver.getSmnTopicUrn());
var body = new PublishMessageRequestBody()
.withSubject(bundle.getString("alerter.notify.title"))
.withMessage(renderContent(noticeTemplate, alert));
request.withBody(body);
var response = smnClient.publishMessage(request);
log.debug("huaweiCloud smn alert response: {}", response);
} catch (Exception e) {
throw new AlertNoticeException("[Huawei Cloud Smn Notify Error] " + e.getMessage());
}
}
private SmnClient getSmnClient(NoticeReceiver receiver) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 11;
}
}
|
var key = receiver.getSmnProjectId() + receiver.getSmnAk() + receiver.getSmnSk() + receiver.getSmnRegion();
if (smnClientMap.containsKey(key)) {
return smnClientMap.get(key);
}
var auth = new BasicCredentials()
.withProjectId(receiver.getSmnProjectId())
.withAk(receiver.getSmnAk())
.withSk(receiver.getSmnSk());
var smnAsyncClient = SmnClient.newBuilder()
.withCredential(auth)
.withRegion(SmnRegion.valueOf(receiver.getSmnRegion()))
.build();
smnClientMap.put(key, smnAsyncClient);
return smnAsyncClient;
| 329
| 202
| 531
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/ServerChanAlertNotifyHandlerImpl.java
|
ServerChanAlertNotifyHandlerImpl
|
send
|
class ServerChanAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
/**
* 发送报警通知
*
* @param receiver Notification configuration information 通知配置信息
* @param alert Alarm information 告警信息
* @throws AlertNoticeException when send receiver error
*/
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
/**
* 通知类型
*
* @return 通知类型
*/
@Override
public byte type() {
return 12;
}
@Data
private static class ServerChanWebHookDto {
private static final String MARKDOWN = "markdown";
/**
* 标题
*/
private String title;
/**
* markdown消息内容
*/
private String desp;
}
}
|
try {
ServerChanAlertNotifyHandlerImpl.ServerChanWebHookDto serverChanWebHookDto = new ServerChanAlertNotifyHandlerImpl.ServerChanWebHookDto();
serverChanWebHookDto.setTitle(bundle.getString("alerter.notify.title"));
serverChanWebHookDto.setDesp(renderContent(noticeTemplate, alert));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<ServerChanAlertNotifyHandlerImpl.ServerChanWebHookDto> httpEntity = new HttpEntity<>(serverChanWebHookDto, headers);
String webHookUrl = String.format(alerterProperties.getServerChanWebhookUrl(), receiver.getServerChanToken());
ResponseEntity<CommonRobotNotifyResp> responseEntity = restTemplate.postForEntity(webHookUrl,
httpEntity, CommonRobotNotifyResp.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
log.debug("Send ServerChan webHook: {} Success", webHookUrl);
} else {
log.warn("Send ServerChan webHook: {} Failed: {}", webHookUrl, responseEntity.getBody());
throw new AlertNoticeException("Http StatusCode " + responseEntity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[ServerChan Notify Error] " + e.getMessage());
}
| 246
| 373
| 619
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/SlackAlertNotifyHandlerImpl.java
|
SlackAlertNotifyHandlerImpl
|
send
|
class SlackAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private static final String SUCCESS = "ok";
private final RestTemplate restTemplate;
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 8;
}
@Data
@Builder
private static class SlackNotifyDTO {
private String text;
}
}
|
try {
var slackNotify = SlackNotifyDTO.builder()
.text(renderContent(noticeTemplate, alert))
.build();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<SlackNotifyDTO> slackNotifyEntity = new HttpEntity<>(slackNotify, headers);
var entity = restTemplate.postForEntity(receiver.getSlackWebHookUrl(), slackNotifyEntity, String.class);
if (entity.getStatusCode() == HttpStatus.OK && entity.getBody() != null) {
var body = entity.getBody();
if (Objects.equals(SUCCESS, body)) {
log.debug("Send Slack Success");
} else {
log.warn("Send Slack Failed: {}", body);
throw new AlertNoticeException(body);
}
} else {
log.warn("Send Slack Failed {}", entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[Slack Notify Error] " + e.getMessage());
}
| 138
| 307
| 445
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/SmsAlertNotifyHandlerImpl.java
|
SmsAlertNotifyHandlerImpl
|
send
|
class SmsAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private final TencentSmsClient tencentSmsClient;
private final ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 0;
}
}
|
// SMS notification 短信通知
try {
String monitorName = null;
if (alert.getTags() != null) {
monitorName = alert.getTags().get(CommonConstants.TAG_MONITOR_NAME);
}
String[] params = new String[3];
params[0] = monitorName == null ? alert.getTarget() : monitorName;
params[1] = bundle.getString("alerter.priority." + alert.getPriority());
params[2] = alert.getContent();
tencentSmsClient.sendMessage(params, new String[]{receiver.getPhone()});
} catch (Exception e) {
throw new AlertNoticeException("[Sms Notify Error] " + e.getMessage());
}
| 118
| 191
| 309
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/TelegramBotAlertNotifyHandlerImpl.java
|
TelegramBotAlertNotifyHandlerImpl
|
send
|
class TelegramBotAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 7;
}
@Data
@Builder
private static class TelegramBotNotifyDTO {
@JsonProperty("chat_id")
private String chatId;
private String text;
@JsonProperty("disable_web_page_preview")
private Boolean disableWebPagePreview;
}
@NoArgsConstructor
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
private static class TelegramBotNotifyResponse {
private boolean ok;
@JsonProperty("error_code")
private Integer errorCode;
private String description;
}
}
|
try {
String url = String.format(alerterProperties.getTelegramWebhookUrl(), receiver.getTgBotToken());
TelegramBotNotifyDTO notifyBody = TelegramBotNotifyDTO.builder()
.chatId(receiver.getTgUserId())
.text(renderContent(noticeTemplate, alert))
.disableWebPagePreview(true)
.build();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<TelegramBotNotifyDTO> telegramEntity = new HttpEntity<>(notifyBody, headers);
ResponseEntity<TelegramBotNotifyResponse> entity = restTemplate.postForEntity(url, telegramEntity, TelegramBotNotifyResponse.class);
if (entity.getStatusCode() == HttpStatus.OK && entity.getBody() != null) {
TelegramBotNotifyResponse body = entity.getBody();
if (body.ok) {
log.debug("Send Telegram Bot Success");
} else {
log.warn("Send Telegram Bot Failed: {}, error_code: {}", body.description, body.errorCode);
throw new AlertNoticeException(body.description);
}
} else {
log.warn("Send Telegram Bot Failed {}", entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[Telegram Bot Notify Error] " + e.getMessage());
}
| 227
| 385
| 612
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WeChatAlertNotifyHandlerImpl.java
|
WeChatAlertNotifyHandlerImpl
|
send
|
class WeChatAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
private static final Logger log = LoggerFactory.getLogger(WeChatAlertNotifyHandlerImpl.class);
private static final String CORP_ID = "YOUR_CORP_ID";
private static final String CORP_SECRET = "YOUR_CORP_SECRET";
private static final String AGENT_ID = "YOUR_AGENT_ID";
private static final String GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + CORP_SECRET;
private static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
private static final String ACCESS_TOKEN = "access_token";
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
private String getAccessToken() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(GET_TOKEN_URL))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(response.body()).getAsJsonObject();
String accessToken = null;
if (jsonObject.has(ACCESS_TOKEN)) {
accessToken = jsonObject.get(ACCESS_TOKEN).getAsString();
} else {
// todo 处理错误情况,例如记录日志或抛出异常
log.error("Failed to obtain ACCESS_TOKEN from response: {}", response.body());
}
return accessToken;
}
private String constructMessageContent(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {
// 示例:构造一个文本消息内容
JsonObject messageContent = new JsonObject();
messageContent.addProperty("msgtype", "text");
JsonObject textContent = new JsonObject();
// 这里可以根据NoticeTemplate和Alert信息构造消息内容
String alertMessage = String.format("警告:%s\n详情:%s", alert.getAlertDefineId(), alert.getContent());
textContent.addProperty("content", alertMessage);
messageContent.add("text", textContent);
// 如果需要@某人,可以在这里添加
JsonObject atInfo = new JsonObject();
atInfo.addProperty("isAtAll", false); // 是否@所有人
messageContent.add("at", atInfo);
// 返回JSON字符串
return messageContent.toString();
}
private void sendMessage(String accessToken, String messageContent) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(SEND_MESSAGE_URL + accessToken))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(messageContent))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 检查消息是否成功发送
log.info("Message sent response: {}", response.body());
}
@Override
public byte type() {
return 3;
}
}
|
try {
String accessToken = getAccessToken();
String messageContent = constructMessageContent(receiver, noticeTemplate, alert);
sendMessage(accessToken, messageContent);
} catch (Exception e) {
log.error("Failed to send WeChat alert", e);
}
| 915
| 73
| 988
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WeWorkAppAlertNotifyHandlerImpl.java
|
WeWorkAppAlertNotifyHandlerImpl
|
send
|
class WeWorkAppAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
/**
* send weChat app message url
*/
private static final String APP_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s";
/**
* get access_token url
*/
private static final String SECRET_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
/**
* 应用消息发送对象
*/
private static final String DEFAULT_ALL = "@all";
private final RestTemplate restTemplate;
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) throws AlertNoticeException {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 10;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class WeChatAppReq {
@JsonProperty(value = "errcode")
private Integer errCode;
@JsonProperty(value = "errmsg")
private String errMsg;
@JsonProperty(value = "access_token")
private String accessToken;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
private static class WeChatAppDTO {
/**
* markdown格式
*/
public static final String MARKDOWN = "markdown";
@JsonProperty(value = "touser")
private String toUser;
@JsonProperty(value = "toparty")
private String toParty;
@JsonProperty(value = "totag")
private String toTag;
@JsonProperty(value = "msgtype")
private String msgType;
@JsonProperty(value = "agentid")
private Integer agentId;
/**
* text message
*/
private TextDTO text;
/**
* markdown消息
*/
private MarkdownDTO markdown;
@Data
private static class MarkdownDTO {
/**
* 消息内容
*/
private String content;
}
@Data
private static class TextDTO {
/**
* 消息内容
*/
private String content;
}
}
}
|
String corpId = receiver.getCorpId();
Integer agentId = receiver.getAgentId();
String appSecret = receiver.getAppSecret();
try {
ResponseEntity<WeChatAppReq> entityResponse = restTemplate.getForEntity(String.format(SECRET_URL, corpId, appSecret), WeChatAppReq.class);
if (Objects.nonNull(entityResponse.getBody())) {
String accessToken = entityResponse.getBody().getAccessToken();
WeChatAppDTO.MarkdownDTO markdown = new WeChatAppDTO.MarkdownDTO();
markdown.setContent(renderContent(noticeTemplate, alert));
WeChatAppDTO weChatAppDTO = WeChatAppDTO.builder()
.toUser(DEFAULT_ALL)
.msgType(WeChatAppDTO.MARKDOWN)
.markdown(markdown)
.agentId(agentId)
.build();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<WeChatAppDTO> weChatAppEntity = new HttpEntity<>(weChatAppDTO, headers);
ResponseEntity<WeChatAppReq> response = restTemplate.postForEntity(String.format(APP_MESSAGE_URL, accessToken), weChatAppEntity, WeChatAppReq.class);
if (Objects.nonNull(response.getBody()) && !Objects.equals(response.getBody().getErrCode(), 0)) {
log.warn("Send Enterprise WeChat App Error: {}", response.getBody().getErrMsg());
throw new AlertNoticeException("Http StatusCode " + response.getStatusCode() + " Error: " + response.getBody().getErrMsg());
}
}
} catch (Exception e) {
throw new AlertNoticeException("[Enterprise WeChat Notify Error] " + e.getMessage());
}
| 626
| 475
| 1,101
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WeWorkRobotAlertNotifyHandlerImpl.java
|
WeWorkRobotAlertNotifyHandlerImpl
|
send
|
class WeWorkRobotAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 4;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
private static class WeWorkWebHookDto {
public static final String WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
/**
* markdown格式
*/
private static final String MARKDOWN = "markdown";
/**
* 文本格式
*/
private static final String TEXT = "text";
/**
* 消息类型
*/
@Builder.Default
private String msgtype = MARKDOWN;
/**
* markdown消息
*/
private MarkdownDTO markdown;
@Data
private static class MarkdownDTO {
/**
* 消息内容
*/
private String content;
}
}
}
|
try {
WeWorkWebHookDto weWorkWebHookDTO = new WeWorkWebHookDto();
WeWorkWebHookDto.MarkdownDTO markdownDTO = new WeWorkWebHookDto.MarkdownDTO();
markdownDTO.setContent(renderContent(noticeTemplate, alert));
weWorkWebHookDTO.setMarkdown(markdownDTO);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<WeWorkWebHookDto> httpEntity = new HttpEntity<>(weWorkWebHookDTO, headers);
String webHookUrl = alerterProperties.getWeWorkWebhookUrl() + receiver.getWechatId();
ResponseEntity<CommonRobotNotifyResp> entity = restTemplate.postForEntity(webHookUrl, httpEntity, CommonRobotNotifyResp.class);
if (entity.getStatusCode() == HttpStatus.OK) {
assert entity.getBody() != null;
if (entity.getBody().getErrCode() == 0) {
log.debug("Send WeWork webHook: {} Success", webHookUrl);
} else {
log.warn("Send WeWork webHook: {} Failed: {}", webHookUrl, entity.getBody().getErrMsg());
throw new AlertNoticeException(entity.getBody().getErrMsg());
}
} else {
log.warn("Send WeWork webHook: {} Failed: {}", webHookUrl, entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[WeWork Notify Error] " + e.getMessage());
}
| 305
| 429
| 734
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WebHookAlertNotifyHandlerImpl.java
|
WebHookAlertNotifyHandlerImpl
|
send
|
class WebHookAlertNotifyHandlerImpl extends AbstractAlertNotifyHandlerImpl {
@Override
public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert alert) {<FILL_FUNCTION_BODY>}
@Override
public byte type() {
return 2;
}
private void filterInvalidTags(Alert alert) {
if (alert.getTags() == null) {
return;
}
Iterator<Map.Entry<String, String>> iterator = alert.getTags().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (StringUtils.isNoneBlank(entry.getKey(), entry.getValue())) {
continue;
}
iterator.remove();
}
// In order to beautify Freemarker template
if (alert.getTags().entrySet().size() <= 0L) {
alert.setTags(null);
}
}
}
|
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// fix null pointer exception
filterInvalidTags(alert);
String webhookJson = renderContent(noticeTemplate, alert);
webhookJson = webhookJson.replace(",\n }", "\n }");
HttpEntity<String> alertHttpEntity = new HttpEntity<>(webhookJson, headers);
ResponseEntity<String> entity = restTemplate.postForEntity(receiver.getHookUrl(), alertHttpEntity, String.class);
if (entity.getStatusCode().value() < HttpStatus.BAD_REQUEST.value()) {
log.debug("Send WebHook: {} Success", receiver.getHookUrl());
} else {
log.warn("Send WebHook: {} Failed: {}", receiver.getHookUrl(), entity.getBody());
throw new AlertNoticeException("Http StatusCode " + entity.getStatusCode());
}
} catch (Exception e) {
throw new AlertNoticeException("[WebHook Notify Error] " + e.getMessage());
}
| 256
| 273
| 529
|
<methods>public void onEvent(org.apache.hertzbeat.common.support.event.SystemConfigChangeEvent) <variables>protected static final java.time.format.DateTimeFormatter DTF,private static final java.lang.String NUMBER_FORMAT,protected org.apache.hertzbeat.alert.AlerterProperties alerterProperties,protected java.util.ResourceBundle bundle,protected org.apache.hertzbeat.manager.service.NoticeConfigService noticeConfigService,protected RestTemplate restTemplate
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/AngularErrorViewResolver.java
|
AngularErrorViewResolver
|
resolveResource
|
class AngularErrorViewResolver implements ErrorViewResolver, Ordered {
private static final Map<HttpStatus.Series, String> SERIES_VIEWS;
private static final String NOT_FOUND_CODE = "404";
static {
Map<HttpStatus.Series, String> views = new EnumMap<>(HttpStatus.Series.class);
views.put(HttpStatus.Series.CLIENT_ERROR, "4xx");
views.put(HttpStatus.Series.SERVER_ERROR, "5xx");
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
private final ApplicationContext applicationContext;
private final WebProperties.Resources resources;
private final TemplateAvailabilityProviders templateAvailabilityProviders;
private int order = Ordered.LOWEST_PRECEDENCE;
public AngularErrorViewResolver(ApplicationContext applicationContext, WebProperties webProperties) {
Assert.notNull(applicationContext, "ApplicationContext must not be null");
Assert.notNull(webProperties.getResources(), "Resources must not be null");
this.applicationContext = applicationContext;
this.resources = webProperties.getResources();
this.templateAvailabilityProviders = new TemplateAvailabilityProviders(applicationContext);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
if (NOT_FOUND_CODE.equals(viewName)) {
errorViewName = "index";
}
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
return resolveResource(errorViewName, model);
}
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@link View} backed by an HTML resource.
*/
private static class HtmlResourceView implements View {
private final Resource resource;
HtmlResourceView(Resource resource) {
this.resource = resource;
}
@Override
public String getContentType() {
return MediaType.TEXT_HTML_VALUE;
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType(getContentType());
FileCopyUtils.copy(this.resource.getInputStream(), response.getOutputStream());
}
}
}
|
for (String location : this.resources.getStaticLocations()) {
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
} catch (Exception ex) {
log.error("Error resolving resource", ex);
}
}
return null;
| 808
| 118
| 926
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/CommonCommandLineRunner.java
|
CommonCommandLineRunner
|
run
|
class CommonCommandLineRunner implements CommandLineRunner {
private static final Integer LANG_REGION_LENGTH = 2;
@Resource
private SystemGeneralConfigServiceImpl systemGeneralConfigService;
@Resource
private TemplateConfigServiceImpl templateConfigService;
@Resource
private AppService appService;
@Resource
protected GeneralConfigDao generalConfigDao;
@Resource
protected ObjectMapper objectMapper;
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
SystemConfig systemConfig = systemGeneralConfigService.getConfig();
if (systemConfig != null) {
if (systemConfig.getTimeZoneId() != null) {
TimeZone.setDefault(TimeZone.getTimeZone(systemConfig.getTimeZoneId()));
}
if (systemConfig.getLocale() != null) {
String[] arr = systemConfig.getLocale().split(CommonConstants.LOCALE_SEPARATOR);
if (arr.length == LANG_REGION_LENGTH) {
String language = arr[0];
String country = arr[1];
Locale.setDefault(new Locale(language, country));
}
}
} else {
// init system config data
systemConfig = SystemConfig.builder().timeZoneId(TimeZone.getDefault().getID())
.locale(Locale.getDefault().getLanguage() + CommonConstants.LOCALE_SEPARATOR
+ Locale.getDefault().getCountry())
.build();
String contentJson = objectMapper.writeValueAsString(systemConfig);
GeneralConfig generalConfig2Save = GeneralConfig.builder()
.type(systemGeneralConfigService.type())
.content(contentJson)
.build();
generalConfigDao.save(generalConfig2Save);
}
// flush the template config in db to memory
TemplateConfig templateConfig = templateConfigService.getConfig();
appService.updateCustomTemplateConfig(templateConfig);
| 144
| 366
| 510
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/HeaderRequestInterceptor.java
|
HeaderRequestInterceptor
|
intercept
|
class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
// Send json by default
// 默认发送json
if (request.getHeaders().getContentType() == null) {
request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
}
// Use short links 使用短链接
request.getHeaders().add(HttpHeaders.CONNECTION, "close");
return execution.execute(request, body);
| 64
| 101
| 165
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/JpaAuditorConfig.java
|
JpaAuditorConfig
|
getCurrentAuditor
|
class JpaAuditorConfig implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {<FILL_FUNCTION_BODY>}
}
|
SubjectSum subjectSum = SurenessContextHolder.getBindSubject();
String username = null;
if (subjectSum != null) {
Object principal = subjectSum.getPrincipal();
if (principal != null) {
username = String.valueOf(principal);
}
}
return Optional.ofNullable(username);
| 50
| 89
| 139
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/RestTemplateConfig.java
|
RestTemplateConfig
|
restTemplate
|
class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {<FILL_FUNCTION_BODY>}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build();
return new OkHttp3ClientHttpRequestFactory(client);
}
}
|
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setInterceptors(Collections.singletonList(new HeaderRequestInterceptor()));
return restTemplate;
| 144
| 46
| 190
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/SecurityCorsConfiguration.java
|
SecurityCorsConfiguration
|
corsFilter
|
class SecurityCorsConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {<FILL_FUNCTION_BODY>}
}
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
source.registerCorsConfiguration("/**", corsConfiguration);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
bean.setOrder(Integer.MIN_VALUE);
bean.setFilter(new CorsFilter(source));
bean.addUrlPatterns("/*");
return bean;
| 38
| 187
| 225
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/config/SwaggerConfig.java
|
SwaggerConfig
|
springOpenApi
|
class SwaggerConfig {
private static final String SECURITY_SCHEME_NAME = "BearerAuth";
@Bean
public OpenAPI springOpenApi() {<FILL_FUNCTION_BODY>}
}
|
return new OpenAPI()
.info(new Info()
.title("HertzBeat")
.description("An Open-Source Real-time Monitoring Tool.")
.termsOfService("https://hertzbeat.com/")
.contact(new Contact().name("tom").url("https://github.com/tomsun28").email("tomsun28@outlook.com"))
.version("v1.0")
.license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0")))
.externalDocs(new ExternalDocumentation()
.description("HertzBeat Docs").url("https://hertzbeat.com/docs/"))
.addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME))
.components(new Components().addSecuritySchemes(SECURITY_SCHEME_NAME,
new SecurityScheme()
.name(SECURITY_SCHEME_NAME)
.type(SecurityScheme.Type.HTTP)
.scheme("Bearer")
.bearerFormat("JWT")));
| 57
| 291
| 348
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java
|
AccountController
|
authGetToken
|
class AccountController {
/**
* Token validity time in seconds
* TOKEN有效期时间 单位秒
*/
private static final long PERIOD_TIME = 3600L;
/**
* account data provider
*/
private SurenessAccountProvider accountProvider = new DocumentAccountProvider();
@PostMapping("/form")
@Operation(summary = "Account password login to obtain associated user information", description = "账户密码登录获取关联用户信息")
public ResponseEntity<Message<Map<String, String>>> authGetToken(@Valid @RequestBody LoginDto loginDto) {<FILL_FUNCTION_BODY>}
@GetMapping("/refresh/{refreshToken}")
@Operation(summary = "Use refresh TOKEN to re-acquire TOKEN", description = "使用刷新TOKEN重新获取TOKEN")
public ResponseEntity<Message<RefreshTokenResponse>> refreshToken(
@Parameter(description = "Refresh TOKEN | 刷新TOKEN", example = "xxx")
@PathVariable("refreshToken") @NotNull final String refreshToken) {
try {
Claims claims = JsonWebTokenUtil.parseJwt(refreshToken);
String userId = String.valueOf(claims.getSubject());
boolean isRefresh = claims.get("refresh", Boolean.class);
if (userId == null || !isRefresh) {
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Illegal Refresh Token"));
}
SurenessAccount account = accountProvider.loadAccount(userId);
if (account == null) {
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Not Exists This Token Mapping Account"));
}
List<String> roles = account.getOwnRoles();
String issueToken = issueToken(userId, roles, PERIOD_TIME);
String issueRefresh = issueToken(userId, roles, PERIOD_TIME << 5);
RefreshTokenResponse response = new RefreshTokenResponse(issueToken, issueRefresh);
return ResponseEntity.ok(Message.success(response));
} catch (Exception e) {
log.error("Exception occurred during token refresh: {}", e.getClass().getName(), e);
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Refresh Token Expired or Error"));
}
}
private String issueToken(String userId, List<String> roles, long expirationMillis) {
Map<String, Object> customClaimMap = new HashMap<>(1);
customClaimMap.put("refresh", true);
return JsonWebTokenUtil.issueJwt(userId, expirationMillis, roles, customClaimMap);
}
}
|
SurenessAccount account = accountProvider.loadAccount(loginDto.getIdentifier());
if (account == null || account.getPassword() == null) {
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Incorrect Account or Password"));
} else {
String password = loginDto.getCredential();
if (account.getSalt() != null) {
password = Md5Util.md5(password + account.getSalt());
}
if (!account.getPassword().equals(password)) {
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Incorrect Account or Password"));
}
if (account.isDisabledAccount() || account.isExcessiveAttempts()) {
return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "Expired or Illegal Account"));
}
}
// Get the roles the user has - rbac
List<String> roles = account.getOwnRoles();
// Issue TOKEN
String issueToken = JsonWebTokenUtil.issueJwt(loginDto.getIdentifier(), PERIOD_TIME, roles);
Map<String, Object> customClaimMap = new HashMap<>(1);
customClaimMap.put("refresh", true);
String issueRefresh = JsonWebTokenUtil.issueJwt(loginDto.getIdentifier(), PERIOD_TIME << 5, customClaimMap);
Map<String, String> resp = new HashMap<>(2);
resp.put("token", issueToken);
resp.put("refreshToken", issueRefresh);
resp.put("role", JsonUtil.toJson(roles));
return ResponseEntity.ok(Message.success(resp));
| 701
| 450
| 1,151
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java
|
AppController
|
queryAppsHierarchy
|
class AppController {
private static final String[] RISKY_STR_ARR = {"ScriptEngineManager", "URLClassLoader", "!!",
"ClassLoader", "AnnotationConfigApplicationContext", "FileSystemXmlApplicationContext",
"GenericXmlApplicationContext", "GenericGroovyApplicationContext", "GroovyScriptEngine",
"GroovyClassLoader", "GroovyShell", "ScriptEngine", "ScriptEngineFactory", "XmlWebApplicationContext",
"ClassPathXmlApplicationContext", "MarshalOutputStream", "InflaterOutputStream", "FileOutputStream"};
@Autowired
private AppService appService;
@GetMapping(path = "/{app}/params")
@Operation(summary = "The structure of the input parameters required to specify the monitoring type according to the app query", description = "根据app查询指定监控类型的需要输入参数的结构")
public ResponseEntity<Message<List<ParamDefine>>> queryAppParamDefines(
@Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) {
List<ParamDefine> paramDefines = appService.getAppParamDefines(app.toLowerCase());
return ResponseEntity.ok(Message.success(paramDefines));
}
@GetMapping(path = "/{monitorId}/pushdefine")
@Operation(summary = "The definition structure of the specified monitoring type according to the push query", description = "根据monitorId查询push类型的定义结构")
public ResponseEntity<Message<Job>> queryPushDefine(
@Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("monitorId") final Long monitorId) {
Job define = appService.getPushDefine(monitorId);
return ResponseEntity.ok(Message.success(define));
}
@GetMapping(path = "/{monitorId}/define/dynamic")
@Operation(summary = "The definition structure of the specified monitoring type according to the push query", description = "根据monitorId查询push类型的定义结构")
public ResponseEntity<Message<Job>> queryAutoGenerateDynamicAppDefine(
@Parameter(description = "Monitoring id | 监控任务ID", example = "5435345") @PathVariable("monitorId") final Long monitorId) {
Job define = appService.getAutoGenerateDynamicDefine(monitorId);
return ResponseEntity.ok(Message.success(define));
}
@GetMapping(path = "/{app}/define")
@Operation(summary = "The definition structure of the specified monitoring type according to the app query", description = "根据app查询指定监控类型的定义结构")
public ResponseEntity<Message<Job>> queryAppDefine(
@Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) {
Job define = appService.getAppDefine(app.toLowerCase());
return ResponseEntity.ok(Message.success(define));
}
@GetMapping(path = "/{app}/define/yml")
@Operation(summary = "The definition yml of the specified monitoring type according to the app query", description = "根据app查询指定监控类型的定义YML")
public ResponseEntity<Message<String>> queryAppDefineYml(
@Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) {
String defineContent = appService.getMonitorDefineFileContent(app);
return ResponseEntity.ok(Message.successWithData(defineContent));
}
@DeleteMapping(path = "/{app}/define/yml")
@Operation(summary = "Delete monitor define yml", description = "根据app删除指定监控类型的定义YML")
public ResponseEntity<Message<Void>> deleteAppDefineYml(
@Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) {
try {
appService.deleteMonitorDefine(app);
} catch (Exception e) {
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
}
return ResponseEntity.ok(Message.success());
}
@PostMapping(path = "/define/yml")
@Operation(summary = "Add new monitoring type define yml", description = "新增监控类型的定义YML")
public ResponseEntity<Message<Void>> newAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) {
try {
for (String riskyToken : RISKY_STR_ARR) {
if (defineDto.getDefine().contains(riskyToken)) {
return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script"));
}
}
appService.applyMonitorDefineYml(defineDto.getDefine(), false);
} catch (Exception e) {
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
}
return ResponseEntity.ok(Message.success());
}
@PutMapping(path = "/define/yml")
@Operation(summary = "Update monitoring type define yml", description = "更新监控类型的定义YML")
public ResponseEntity<Message<Void>> updateAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) {
try {
for (String riskyToken : RISKY_STR_ARR) {
if (defineDto.getDefine().contains(riskyToken)) {
return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script"));
}
}
appService.applyMonitorDefineYml(defineDto.getDefine(), true);
} catch (Exception e) {
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
}
return ResponseEntity.ok(Message.success());
}
@GetMapping(path = "/hierarchy")
@Operation(summary = "Query all monitor metrics level, output in a hierarchical structure", description = "查询所有监控的类型指标层级,以层级结构输出")
public ResponseEntity<Message<List<Hierarchy>>> queryAppsHierarchy(
@Parameter(description = "en: language type,zh: 语言类型",
example = "zh-CN")
@RequestParam(name = "lang", required = false) String lang) {<FILL_FUNCTION_BODY>}
}
|
if (lang == null || lang.isEmpty()) {
lang = "zh-CN";
}
if (lang.contains(Locale.ENGLISH.getLanguage())) {
lang = "en-US";
} else if (lang.contains(Locale.CHINESE.getLanguage())) {
lang = "zh-CN";
} else {
lang = "en-US";
}
List<Hierarchy> appHierarchies = appService.getAllAppHierarchy(lang);
return ResponseEntity.ok(Message.success(appHierarchies));
| 1,658
| 147
| 1,805
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java
|
CollectorController
|
generateCollectorDeployInfo
|
class CollectorController {
@Autowired
private CollectorService collectorService;
@Autowired(required = false)
private ManageServer manageServer;
@GetMapping
@Operation(summary = "Get a list of collectors based on query filter items",
description = "根据查询过滤项获取采集器列表")
public ResponseEntity<Message<Page<CollectorSummary>>> getCollectors(
@Parameter(description = "collector name", example = "tom") @RequestParam(required = false) final String name,
@Parameter(description = "List current page | 列表当前分页", example = "0") @RequestParam(defaultValue = "0") int pageIndex,
@Parameter(description = "Number of list pagination | 列表分页数量", example = "8") @RequestParam(required = false) Integer pageSize) {
if (pageSize == null) {
pageSize = Integer.MAX_VALUE;
}
Specification<Collector> specification = (root, query, criteriaBuilder) -> {
Predicate predicate = criteriaBuilder.conjunction();
if (name != null && !name.isEmpty()) {
Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%");
predicate = criteriaBuilder.and(predicateName);
}
return predicate;
};
PageRequest pageRequest = PageRequest.of(pageIndex, pageSize);
Page<CollectorSummary> receivers = collectorService.getCollectors(specification, pageRequest);
Message<Page<CollectorSummary>> message = Message.success(receivers);
return ResponseEntity.ok(message);
}
@PutMapping("/online")
@Operation(summary = "Online collectors")
public ResponseEntity<Message<Void>> onlineCollector(
@Parameter(description = "collector name", example = "demo-collector")
@RequestParam(required = false) List<String> collectors) {
if (collectors != null) {
collectors.forEach(collector ->
this.manageServer.getCollectorAndJobScheduler().onlineCollector(collector));
}
return ResponseEntity.ok(Message.success("Online success"));
}
@PutMapping("/offline")
@Operation(summary = "Offline collectors")
public ResponseEntity<Message<Void>> offlineCollector(
@Parameter(description = "collector name", example = "demo-collector")
@RequestParam(required = false) List<String> collectors) {
if (collectors != null) {
collectors.forEach(collector -> this.manageServer.getCollectorAndJobScheduler().offlineCollector(collector));
}
return ResponseEntity.ok(Message.success("Offline success"));
}
@DeleteMapping
@Operation(summary = "Delete collectors")
public ResponseEntity<Message<Void>> deleteCollector(
@Parameter(description = "collector name | 采集器名称", example = "demo-collector")
@RequestParam(required = false) List<String> collectors) {
this.collectorService.deleteRegisteredCollector(collectors);
return ResponseEntity.ok(Message.success("Delete success"));
}
@PostMapping("/generate/{collector}")
@Operation(summary = "Generate deploy collector info")
public ResponseEntity<Message<Map<String, String>>> generateCollectorDeployInfo(
@Parameter(description = "collector name", example = "demo-collector")
@PathVariable() String collector) {<FILL_FUNCTION_BODY>}
}
|
if (this.collectorService.hasCollector(collector)) {
return ResponseEntity.ok(Message.fail(CommonConstants.FAIL_CODE, "There already has same collector name."));
}
String host = IpDomainUtil.getLocalhostIp();
Map<String, String> maps = new HashMap<>(6);
maps.put("identity", collector);
maps.put("host", host);
return ResponseEntity.ok(Message.success(maps));
| 901
| 120
| 1,021
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java
|
GeneralConfigController
|
getConfig
|
class GeneralConfigController {
private Map<String, GeneralConfigService> configServiceMap;
public GeneralConfigController(List<GeneralConfigService> generalConfigServices) {
configServiceMap = new HashMap<>(8);
if (generalConfigServices != null) {
generalConfigServices.forEach(config -> configServiceMap.put(config.type(), config));
}
}
@PostMapping(path = "/{type}")
@Operation(summary = "Save or update common config", description = "保存公共配置")
public ResponseEntity<Message<String>> saveOrUpdateConfig(
@Parameter(description = "Config Type", example = "email")
@PathVariable("type") @NotNull final String type,
@RequestBody Object config) {
GeneralConfigService configService = configServiceMap.get(type);
if (configService == null) {
throw new IllegalArgumentException("Not supported this config type: " + type);
}
configService.saveConfig(config);
return ResponseEntity.ok(Message.success("Update config success"));
}
@GetMapping(path = "/{type}")
@Operation(summary = "Get the sender config", description = "获取发送端配置")
public ResponseEntity<Message<Object>> getConfig(
@Parameter(description = "Config Type", example = "email")
@PathVariable("type") @NotNull final String type) {<FILL_FUNCTION_BODY>}
@PutMapping(path = "/template/{app}")
@Operation(summary = "Update the app template config")
public ResponseEntity<Message<Void>> updateTemplateAppConfig(
@PathVariable("app") @NotNull final String app,
@RequestBody TemplateConfig.AppTemplate template) {
GeneralConfigService configService = configServiceMap.get("template");
if (configService == null || !(configService instanceof TemplateConfigServiceImpl)) {
throw new IllegalArgumentException("Not supported this config type: template");
}
TemplateConfig config = ((TemplateConfigServiceImpl) configService).getConfig();
if (config == null) {
config = new TemplateConfig();
}
if (config.getApps() == null) {
config.setApps(new HashMap<>(8));
}
config.getApps().put(app, template);
configService.saveConfig(config);
return ResponseEntity.ok(Message.success());
}
}
|
GeneralConfigService configService = configServiceMap.get(type);
if (configService == null) {
throw new IllegalArgumentException("Not supported this config type: " + type);
}
return ResponseEntity.ok(Message.success(configService.getConfig()));
| 588
| 67
| 655
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/I18nController.java
|
I18nController
|
queryI18n
|
class I18nController {
@Autowired
private AppService appService;
@GetMapping("/{lang}")
@Operation(summary = "Query total i 18 n internationalized text resources", description = "查询总的i18n国际化文本资源")
public ResponseEntity<Message<Map<String, String>>> queryI18n(
@Parameter(description = "en: language type,zh: 语言类型", example = "zh-CN")
@PathVariable(name = "lang", required = false) String lang) {<FILL_FUNCTION_BODY>}
}
|
if (lang == null || lang.isEmpty()) {
lang = "zh-CN";
}
lang = "zh-cn".equalsIgnoreCase(lang) || "zh_cn".equalsIgnoreCase(lang) ? "zh-CN" : lang;
lang = "en-us".equalsIgnoreCase(lang) || "en_us".equalsIgnoreCase(lang) ? "en-US" : lang;
Map<String, String> i18nResource = appService.getI18nResources(lang);
return ResponseEntity.ok(Message.success(i18nResource));
| 152
| 148
| 300
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/MetricsController.java
|
MetricsController
|
getMetricsInfo
|
class MetricsController {
@Autowired
private CommonDataQueue commonDataQueue;
@GetMapping()
@Operation(summary = "Get Hertzbeat Metrics Data")
public ResponseEntity<Message<Map<String, Object>>> getMetricsInfo() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> metricsInfo = new HashMap<>(8);
if (commonDataQueue instanceof InMemoryCommonDataQueue) {
Map<String, Integer> queueInfo = ((InMemoryCommonDataQueue) commonDataQueue).getQueueSizeMetricsInfo();
metricsInfo.putAll(queueInfo);
}
return ResponseEntity.ok(Message.success(metricsInfo));
| 80
| 94
| 174
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/MonitorController.java
|
MonitorController
|
getMonitor
|
class MonitorController {
@Autowired
private MonitorService monitorService;
@PostMapping
@Operation(summary = "Add a monitoring application", description = "新增一个监控应用")
public ResponseEntity<Message<Void>> addNewMonitor(@Valid @RequestBody MonitorDto monitorDto) {
// Verify request data 校验请求数据
monitorService.validate(monitorDto, false);
if (monitorDto.isDetected()) {
// Probe 进行探测
monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
}
monitorService.addMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
return ResponseEntity.ok(Message.success("Add success"));
}
@PutMapping
@Operation(summary = "Modify an existing monitoring application", description = "修改一个已存在监控应用")
public ResponseEntity<Message<Void>> modifyMonitor(@Valid @RequestBody MonitorDto monitorDto) {
// Verify request data 校验请求数据
monitorService.validate(monitorDto, true);
if (monitorDto.isDetected()) {
// Probe 进行探测
monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
}
monitorService.modifyMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
return ResponseEntity.ok(Message.success("Modify success"));
}
@GetMapping(path = "/{id}")
@Operation(summary = "Obtain monitoring information based on monitoring ID", description = "根据监控任务ID获取监控信息")
public ResponseEntity<Message<MonitorDto>> getMonitor(
@Parameter(description = "监控任务ID", example = "6565463543") @PathVariable("id") final long id) {<FILL_FUNCTION_BODY>}
@DeleteMapping(path = "/{id}")
@Operation(summary = "Delete monitoring application based on monitoring ID", description = "根据监控任务ID删除监控应用")
public ResponseEntity<Message<Void>> deleteMonitor(
@Parameter(description = "en: Monitor ID,zh: 监控任务ID", example = "6565463543") @PathVariable("id") final long id) {
// delete monitor 删除监控
Monitor monitor = monitorService.getMonitor(id);
if (monitor == null) {
return ResponseEntity.ok(Message.success("The specified monitoring was not queried, please check whether the parameters are correct"));
}
monitorService.deleteMonitor(id);
return ResponseEntity.ok(Message.success("Delete success"));
}
@PostMapping(path = "/detect")
@Operation(summary = "Perform availability detection on this monitoring based on monitoring information", description = "根据监控信息去对此监控进行可用性探测")
public ResponseEntity<Message<Void>> detectMonitor(@Valid @RequestBody MonitorDto monitorDto) {
monitorService.validate(monitorDto, null);
monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
return ResponseEntity.ok(Message.success("Detect success."));
}
@PostMapping("/optional")
@Operation(summary = "Add a monitor that can select metrics", description = "新增一个可选指标的监控器")
public ResponseEntity<Message<Void>> addNewMonitorOptionalMetrics(@Valid @RequestBody MonitorDto monitorDto) {
monitorService.validate(monitorDto, false);
if (monitorDto.isDetected()) {
monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector());
}
monitorService.addNewMonitorOptionalMetrics(monitorDto.getMetrics(), monitorDto.getMonitor(), monitorDto.getParams());
return ResponseEntity.ok(Message.success("Add success"));
}
@GetMapping(value = {"/metric/{app}", "/metric"})
@Operation(summary = "get app metric", description = "根据app名称获取该app可监控指标,不传为获取全部指标")
public ResponseEntity<Message<List<String>>> getMonitorMetrics(
@PathVariable(value = "app", required = false) String app) {
List<String> metricNames = monitorService.getMonitorMetrics(app);
return ResponseEntity.ok(Message.success(metricNames));
}
}
|
// Get monitoring information
// 获取监控信息
MonitorDto monitorDto = monitorService.getMonitorDto(id);
if (monitorDto == null) {
return ResponseEntity.ok(Message.fail(MONITOR_NOT_EXIST_CODE, "Monitor not exist."));
} else {
return ResponseEntity.ok(Message.success(monitorDto));
}
| 1,137
| 99
| 1,236
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/StatusPageController.java
|
StatusPageController
|
queryStatusPageOrg
|
class StatusPageController {
@Autowired
private StatusPageService statusPageService;
@GetMapping("/org")
@Operation(summary = "Query Status Page Organization")
public ResponseEntity<Message<StatusPageOrg>> queryStatusPageOrg() {<FILL_FUNCTION_BODY>}
@PostMapping("/org")
@Operation(summary = "Save and Update Query Status Page Organization")
public ResponseEntity<Message<StatusPageOrg>> saveStatusPageOrg(@Valid @RequestBody StatusPageOrg statusPageOrg) {
StatusPageOrg org = statusPageService.saveStatusPageOrg(statusPageOrg);
return ResponseEntity.ok(Message.success(org));
}
@GetMapping("/component")
@Operation(summary = "Query Status Page Components")
public ResponseEntity<Message<List<StatusPageComponent>>> queryStatusPageComponent() {
List<StatusPageComponent> statusPageComponents = statusPageService.queryStatusPageComponents();
return ResponseEntity.ok(Message.success(statusPageComponents));
}
@PostMapping("/component")
@Operation(summary = "Save Status Page Component")
public ResponseEntity<Message<Void>> newStatusPageComponent(@Valid @RequestBody StatusPageComponent statusPageComponent) {
statusPageService.newStatusPageComponent(statusPageComponent);
return ResponseEntity.ok(Message.success("Add success"));
}
@PutMapping("/component")
@Operation(summary = "Update Status Page Component")
public ResponseEntity<Message<Void>> updateStatusPageComponent(@Valid @RequestBody StatusPageComponent statusPageComponent) {
statusPageService.updateStatusPageComponent(statusPageComponent);
return ResponseEntity.ok(Message.success("Update success"));
}
@DeleteMapping("/component/{id}")
@Operation(summary = "Delete Status Page Component")
public ResponseEntity<Message<Void>> deleteStatusPageComponent(@PathVariable("id") final long id) {
statusPageService.deleteStatusPageComponent(id);
return ResponseEntity.ok(Message.success("Delete success"));
}
@GetMapping("/component/{id}")
@Operation(summary = "Query Status Page Component")
public ResponseEntity<Message<StatusPageComponent>> queryStatusPageComponent(@PathVariable("id") final long id) {
StatusPageComponent statusPageComponent = statusPageService.queryStatusPageComponent(id);
return ResponseEntity.ok(Message.success(statusPageComponent));
}
@PostMapping("/incident")
@Operation(summary = "Save Status Page Incident")
public ResponseEntity<Message<Void>> newStatusPageIncident(@Valid @RequestBody StatusPageIncident incident) {
statusPageService.newStatusPageIncident(incident);
return ResponseEntity.ok(Message.success("Add success"));
}
@PutMapping("/incident")
@Operation(summary = "Update Status Page Incident")
public ResponseEntity<Message<Void>> updateStatusPageIncident(@Valid @RequestBody StatusPageIncident incident) {
statusPageService.updateStatusPageIncident(incident);
return ResponseEntity.ok(Message.success("Update success"));
}
@DeleteMapping("/incident/{id}")
@Operation(summary = "Delete Status Page Incident")
public ResponseEntity<Message<Void>> deleteStatusPageIncident(@PathVariable("id") final long id) {
statusPageService.deleteStatusPageIncident(id);
return ResponseEntity.ok(Message.success("Delete success"));
}
@GetMapping("/incident/{id}")
@Operation(summary = "Get Status Page Incident")
public ResponseEntity<Message<StatusPageIncident>> queryStatusPageIncident(@PathVariable("id") final long id) {
StatusPageIncident incident = statusPageService.queryStatusPageIncident(id);
return ResponseEntity.ok(Message.success(incident));
}
@GetMapping("/incident")
@Operation(summary = "Query Status Page Incidents")
public ResponseEntity<Message<List<StatusPageIncident>>> queryStatusPageIncident() {
List<StatusPageIncident> incidents = statusPageService.queryStatusPageIncidents();
return ResponseEntity.ok(Message.success(incidents));
}
}
|
StatusPageOrg statusPageOrg = statusPageService.queryStatusPageOrg();
if (statusPageOrg == null) {
return ResponseEntity.ok(Message.fail(CommonConstants.FAIL_CODE, "Status Page Organization Not Found"));
}
return ResponseEntity.ok(Message.success(statusPageOrg));
| 1,060
| 83
| 1,143
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/StatusPagePublicController.java
|
StatusPagePublicController
|
queryStatusPageOrg
|
class StatusPagePublicController {
@Autowired
private StatusPageService statusPageService;
@GetMapping("/org")
@Operation(summary = "Query Status Page Organization")
public ResponseEntity<Message<StatusPageOrg>> queryStatusPageOrg() {<FILL_FUNCTION_BODY>}
@GetMapping("/component")
@Operation(summary = "Query Status Page Components")
public ResponseEntity<Message<List<ComponentStatus>>> queryStatusPageComponent() {
List<ComponentStatus> componentStatusList = statusPageService.queryComponentsStatus();
return ResponseEntity.ok(Message.success(componentStatusList));
}
@GetMapping("/component/{id}")
@Operation(summary = "Query Status Page Component")
public ResponseEntity<Message<ComponentStatus>> queryStatusPageComponent(@PathVariable("id") final long id) {
ComponentStatus componentStatus = statusPageService.queryComponentStatus(id);
return ResponseEntity.ok(Message.success(componentStatus));
}
@GetMapping("/incident")
@Operation(summary = "Query Status Page Incidents")
public ResponseEntity<Message<List<StatusPageIncident>>> queryStatusPageIncident() {
List<StatusPageIncident> incidents = statusPageService.queryStatusPageIncidents();
return ResponseEntity.ok(Message.success(incidents));
}
}
|
StatusPageOrg statusPageOrg = statusPageService.queryStatusPageOrg();
if (statusPageOrg == null) {
return ResponseEntity.ok(Message.fail(CommonConstants.FAIL_CODE, "Status Page Organization Not Found"));
}
return ResponseEntity.ok(Message.success(statusPageOrg));
| 340
| 83
| 423
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/SummaryController.java
|
SummaryController
|
appMonitors
|
class SummaryController {
@Autowired
private MonitorService monitorService;
@GetMapping
@Operation(summary = "Query all application category monitoring statistics", description = "查询所有应用类别监控统计信息")
public ResponseEntity<Message<Dashboard>> appMonitors() {<FILL_FUNCTION_BODY>}
}
|
List<AppCount> appsCount = monitorService.getAllAppMonitorsCount();
Message<Dashboard> message = Message.success(new Dashboard(appsCount));
return ResponseEntity.ok(message);
| 85
| 54
| 139
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/controller/TagController.java
|
TagController
|
getTags
|
class TagController {
@Autowired
private TagService tagService;
@PostMapping
@Operation(summary = "Add Tag", description = "新增标签")
public ResponseEntity<Message<Void>> addNewTags(@Valid @RequestBody List<Tag> tags) {
// Verify request data 校验请求数据 去重
tags = tags.stream().peek(tag -> {
tag.setType((byte) 1);
tag.setId(null);
}).distinct().collect(Collectors.toList());
tagService.addTags(tags);
return ResponseEntity.ok(Message.success("Add success"));
}
@PutMapping
@Operation(summary = "Modify an existing tag", description = "修改一个已存在标签")
public ResponseEntity<Message<Void>> modifyMonitor(@Valid @RequestBody Tag tag) {
// Verify request data 校验请求数据
if (tag.getId() == null || tag.getName() == null) {
throw new IllegalArgumentException("The Tag not exist.");
}
tagService.modifyTag(tag);
return ResponseEntity.ok(Message.success("Modify success"));
}
@GetMapping()
@Operation(summary = "Get tags information", description = "根据条件获取标签信息")
public ResponseEntity<Message<Page<Tag>>> getTags(
@Parameter(description = "Tag content search | 标签内容模糊查询", example = "status") @RequestParam(required = false) String search,
@Parameter(description = "Tag type | 标签类型", example = "0") @RequestParam(required = false) Byte type,
@Parameter(description = "List current page | 列表当前分页", example = "0") @RequestParam(defaultValue = "0") int pageIndex,
@Parameter(description = "Number of list pagination | 列表分页数量", example = "8") @RequestParam(defaultValue = "8") int pageSize) {<FILL_FUNCTION_BODY>}
@DeleteMapping()
@Operation(summary = "Delete tags based on ID", description = "根据TAG ID删除TAG")
public ResponseEntity<Message<Void>> deleteTags(
@Parameter(description = "TAG IDs | 监控任务ID列表", example = "6565463543") @RequestParam(required = false) List<Long> ids) {
if (ids != null && !ids.isEmpty()) {
tagService.deleteTags(new HashSet<>(ids));
}
return ResponseEntity.ok(Message.success("Delete success"));
}
}
|
// Get tag information
Specification<Tag> specification = (root, query, criteriaBuilder) -> {
List<Predicate> andList = new ArrayList<>();
if (type != null) {
Predicate predicateApp = criteriaBuilder.equal(root.get("type"), type);
andList.add(predicateApp);
}
Predicate[] andPredicates = new Predicate[andList.size()];
Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates));
List<Predicate> orList = new ArrayList<>();
if (search != null && !search.isEmpty()) {
Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + search + "%");
orList.add(predicateName);
Predicate predicateValue = criteriaBuilder.like(root.get("value"), "%" + search + "%");
orList.add(predicateValue);
}
Predicate[] orPredicates = new Predicate[orList.size()];
Predicate orPredicate = criteriaBuilder.or(orList.toArray(orPredicates));
if (andPredicate.getExpressions().isEmpty() && orPredicate.getExpressions().isEmpty()) {
return query.where().getRestriction();
} else if (andPredicate.getExpressions().isEmpty()) {
return query.where(orPredicate).getRestriction();
} else if (orPredicate.getExpressions().isEmpty()) {
return query.where(andPredicate).getRestriction();
} else {
return query.where(andPredicate, orPredicate).getRestriction();
}
};
PageRequest pageRequest = PageRequest.of(pageIndex, pageSize);
Page<Tag> alertPage = tagService.getTags(specification, pageRequest);
Message<Page<Tag>> message = Message.success(alertPage);
return ResponseEntity.ok(message);
| 645
| 482
| 1,127
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/nativex/HertzbeatRuntimeHintsRegistrar.java
|
HertzbeatRuntimeHintsRegistrar
|
registerHints
|
class HertzbeatRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
private static final String SshConstantsClassName = "org.apache.sshd.common.SshConstants";
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
private void registerConstructor(RuntimeHints hints, Class<?> clazz) {
Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor<?> declaredConstructor : declaredConstructors) {
hints.reflection().registerConstructor(declaredConstructor, ExecutableMode.INVOKE);
}
}
}
|
// see: https://github.com/spring-cloud/spring-cloud-config/blob/main/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerRuntimeHints.java
// TODO: move over to GraalVM reachability metadata
if (ClassUtils.isPresent(SshConstantsClassName, classLoader)) {
hints.reflection().registerTypes(Set.of(TypeReference.of(BouncyCastleSecurityProviderRegistrar.class),
TypeReference.of(EdDSASecurityProviderRegistrar.class), TypeReference.of(Nio2ServiceFactory.class),
TypeReference.of(Nio2ServiceFactoryFactory.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
hints.reflection().registerTypes(Set.of(TypeReference.of(PortForwardingEventListener.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
hints.proxies().registerJdkProxy(TypeReference.of(ChannelListener.class),
TypeReference.of(PortForwardingEventListener.class), TypeReference.of(SessionListener.class));
}
| 171
| 334
| 505
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/AssignJobs.java
|
AssignJobs
|
removePinnedJob
|
class AssignJobs {
/**
* current assign jobIds
*/
private Set<Long> jobs;
/**
* jobs to be adding
*/
private Set<Long> addingJobs;
/**
* jobs to be removed
*/
private Set<Long> removingJobs;
/**
* jobs has pinned in this collector
*/
private Set<Long> pinnedJobs;
public AssignJobs() {
jobs = ConcurrentHashMap.newKeySet(16);
addingJobs = ConcurrentHashMap.newKeySet(16);
removingJobs = ConcurrentHashMap.newKeySet(16);
pinnedJobs = ConcurrentHashMap.newKeySet(16);
}
public void addAssignJob(Long jobId) {
jobs.add(jobId);
}
public void addAddingJob(Long jobId) {
addingJobs.add(jobId);
}
public void addRemovingJob(Long jobId) {
removingJobs.add(jobId);
}
public void addPinnedJob(Long jobId) {
pinnedJobs.add(jobId);
}
public void addAssignJobs(Set<Long> jobSet) {
if (jobSet != null && !jobSet.isEmpty()) {
jobs.addAll(jobSet);
}
}
public void addAddingJobs(Set<Long> jobSet) {
if (jobSet != null && !jobSet.isEmpty()) {
addingJobs.addAll(jobSet);
}
}
public void addRemovingJobs(Set<Long> jobSet) {
if (jobSet != null && !jobSet.isEmpty()) {
removingJobs.addAll(jobSet);
}
}
public void addPinnedJobs(Set<Long> jobSet) {
if (jobSet != null && !jobSet.isEmpty()) {
pinnedJobs.addAll(jobSet);
}
}
public void removeAssignJobs(Set<Long> jobIds) {
if (jobs == null || jobIds == null || jobIds.isEmpty()) {
return;
}
jobs.removeAll(jobIds);
}
public void removeAddingJobs(Set<Long> jobIds) {
if (addingJobs == null || jobIds == null || jobIds.isEmpty()) {
return;
}
addingJobs.removeAll(jobIds);
}
public void clearRemovingJobs() {
if (removingJobs == null) {
return;
}
removingJobs.clear();
}
/**
* 判断是否存在对应的jobId
* @param jobId jobId
* @return 若存在返回true,并把jobId从assignJobs remove掉
*/
public boolean containAndRemoveJob(Long jobId) {
if (jobs.isEmpty()) {
return false;
}
return jobs.remove(jobId);
}
public void removeAddingJob(Long jobId) {
if (addingJobs == null || jobId == null) {
return;
}
addingJobs.remove(jobId);
}
public void removeRemovingJob(Long jobId) {
if (removingJobs == null || jobId == null) {
return;
}
removingJobs.remove(jobId);
}
public void removePinnedJob(Long jobId) {<FILL_FUNCTION_BODY>}
/**
* 清理数据
*/
public void clear() {
if (!jobs.isEmpty()) {
log.warn("assign jobs is not empty, maybe there are jobs not assigned");
jobs.clear();
}
}
}
|
if (pinnedJobs == null || jobId == null) {
return;
}
pinnedJobs.remove(jobId);
| 989
| 39
| 1,028
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/ConcurrentTreeMap.java
|
ConcurrentTreeMap
|
put
|
class ConcurrentTreeMap<K, V> extends TreeMap<K, V> {
private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public ConcurrentTreeMap() {
super();
}
@Override
public V put(K key, V value) {<FILL_FUNCTION_BODY>}
@Override
public V remove(Object key) {
readWriteLock.writeLock().lock();
try {
return super.remove(key);
} finally {
readWriteLock.writeLock().unlock();
}
}
@Override
public Map.Entry<K, V> firstEntry() {
readWriteLock.readLock().lock();
try {
return super.firstEntry();
} finally {
readWriteLock.readLock().unlock();
}
}
@Override
public Map.Entry<K, V> higherEntry(K key) {
readWriteLock.readLock().lock();
try {
return super.higherEntry(key);
} finally {
readWriteLock.readLock().unlock();
}
}
@Override
public Map.Entry<K, V> ceilingEntry(K key) {
readWriteLock.readLock().lock();
try {
return super.ceilingEntry(key);
} finally {
readWriteLock.readLock().unlock();
}
}
}
|
readWriteLock.writeLock().lock();
try {
return super.put(key, value);
} finally {
readWriteLock.writeLock().unlock();
}
| 360
| 48
| 408
|
<methods>public void <init>() ,public void <init>(Comparator<? super K>) ,public void <init>(Map<? extends K,? extends V>) ,public void <init>(SortedMap<K,? extends V>) ,public Entry<K,V> ceilingEntry(K) ,public K ceilingKey(K) ,public void clear() ,public java.lang.Object clone() ,public Comparator<? super K> comparator() ,public V compute(K, BiFunction<? super K,? super V,? extends V>) ,public V computeIfAbsent(K, Function<? super K,? extends V>) ,public V computeIfPresent(K, BiFunction<? super K,? super V,? extends V>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public NavigableSet<K> descendingKeySet() ,public NavigableMap<K,V> descendingMap() ,public Set<Entry<K,V>> entrySet() ,public Entry<K,V> firstEntry() ,public K firstKey() ,public Entry<K,V> floorEntry(K) ,public K floorKey(K) ,public void forEach(BiConsumer<? super K,? super V>) ,public V get(java.lang.Object) ,public SortedMap<K,V> headMap(K) ,public NavigableMap<K,V> headMap(K, boolean) ,public Entry<K,V> higherEntry(K) ,public K higherKey(K) ,public Set<K> keySet() ,public Entry<K,V> lastEntry() ,public K lastKey() ,public Entry<K,V> lowerEntry(K) ,public K lowerKey(K) ,public V merge(K, V, BiFunction<? super V,? super V,? extends V>) ,public NavigableSet<K> navigableKeySet() ,public Entry<K,V> pollFirstEntry() ,public Entry<K,V> pollLastEntry() ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V putIfAbsent(K, V) ,public V remove(java.lang.Object) ,public V replace(K, V) ,public boolean replace(K, V, V) ,public void replaceAll(BiFunction<? super K,? super V,? extends V>) ,public int size() ,public SortedMap<K,V> subMap(K, K) ,public NavigableMap<K,V> subMap(K, boolean, K, boolean) ,public SortedMap<K,V> tailMap(K) ,public NavigableMap<K,V> tailMap(K, boolean) ,public Collection<V> values() <variables>private static final boolean BLACK,private static final boolean RED,private static final java.lang.Object UNBOUNDED,private final Comparator<? super K> comparator,private transient NavigableMap<K,V> descendingMap,private transient EntrySet entrySet,private transient int modCount,private transient KeySet<K> navigableKeySet,private transient Entry<K,V> root,private static final long serialVersionUID,private transient int size
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/SchedulerInit.java
|
SchedulerInit
|
run
|
class SchedulerInit implements CommandLineRunner {
@Autowired
private CollectorScheduling collectorScheduling;
@Autowired
private CollectJobScheduling collectJobScheduling;
private static final String MAIN_COLLECTOR_NODE_IP = "127.0.0.1";
@Autowired
private AppService appService;
@Autowired
private MonitorDao monitorDao;
@Autowired
private ParamDao paramDao;
@Autowired
private CollectorDao collectorDao;
@Autowired
private CollectorMonitorBindDao collectorMonitorBindDao;
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// init pre collector status
List<Collector> collectors = collectorDao.findAll().stream()
.peek(item -> item.setStatus(CommonConstants.COLLECTOR_STATUS_OFFLINE))
.collect(Collectors.toList());
collectorDao.saveAll(collectors);
// insert default consistent node
CollectorInfo collectorInfo = CollectorInfo.builder()
.name(CommonConstants.MAIN_COLLECTOR_NODE)
.ip(MAIN_COLLECTOR_NODE_IP)
.build();
collectorScheduling.collectorGoOnline(CommonConstants.MAIN_COLLECTOR_NODE, collectorInfo);
// init jobs
List<Monitor> monitors = monitorDao.findMonitorsByStatusNotInAndAndJobIdNotNull(List.of((byte) 0));
List<CollectorMonitorBind> monitorBinds = collectorMonitorBindDao.findAll();
Map<Long, String> monitorIdCollectorMap = monitorBinds.stream().collect(
Collectors.toMap(CollectorMonitorBind::getMonitorId, CollectorMonitorBind::getCollector));
for (Monitor monitor : monitors) {
try {
// 构造采集任务Job实体
Job appDefine = appService.getAppDefine(monitor.getApp());
if (CommonConstants.PROMETHEUS.equals(monitor.getApp())) {
appDefine.setApp(CommonConstants.PROMETHEUS_APP_PREFIX + monitor.getName());
}
appDefine.setId(monitor.getJobId());
appDefine.setMonitorId(monitor.getId());
appDefine.setInterval(monitor.getIntervals());
appDefine.setCyclic(true);
appDefine.setTimestamp(System.currentTimeMillis());
List<Param> params = paramDao.findParamsByMonitorId(monitor.getId());
List<Configmap> configmaps = params.stream()
.map(param -> new Configmap(param.getField(), param.getValue(),
param.getType())).collect(Collectors.toList());
List<ParamDefine> paramDefaultValue = appDefine.getParams().stream()
.filter(item -> StringUtils.hasText(item.getDefaultValue()))
.collect(Collectors.toList());
paramDefaultValue.forEach(defaultVar -> {
if (configmaps.stream().noneMatch(item -> item.getKey().equals(defaultVar.getField()))) {
// todo type
Configmap configmap = new Configmap(defaultVar.getField(), defaultVar.getDefaultValue(), (byte) 1);
configmaps.add(configmap);
}
});
appDefine.setConfigmap(configmaps);
String collector = monitorIdCollectorMap.get(monitor.getId());
long jobId = collectJobScheduling.addAsyncCollectJob(appDefine, collector);
monitor.setJobId(jobId);
monitorDao.save(monitor);
} catch (Exception e) {
log.error("init monitor job: {} error,continue next monitor", monitor, e);
}
}
| 208
| 772
| 980
|
<no_super_class>
|
apache_hertzbeat
|
hertzbeat/manager/src/main/java/org/apache/hertzbeat/manager/scheduler/netty/ManageServer.java
|
ManageServer
|
sendMsgSync
|
class ManageServer implements CommandLineRunner {
private final CollectorAndJobScheduler collectorAndJobScheduler;
private ScheduledExecutorService channelSchedule;
private RemotingServer remotingServer;
private final Map<String, Channel> clientChannelTable = new ConcurrentHashMap<>(16);
public ManageServer(final SchedulerProperties schedulerProperties,
final CollectorAndJobScheduler collectorAndJobScheduler,
final CommonThreadPool threadPool) {
this.collectorAndJobScheduler = collectorAndJobScheduler;
this.collectorAndJobScheduler.setManageServer(this);
this.init(schedulerProperties, threadPool);
}
private void init(final SchedulerProperties schedulerProperties, final CommonThreadPool threadPool) {
NettyServerConfig nettyServerConfig = new NettyServerConfig();
nettyServerConfig.setPort(schedulerProperties.getServer().getPort());
nettyServerConfig.setIdleStateEventTriggerTime(schedulerProperties.getServer().getIdleStateEventTriggerTime());
NettyEventListener nettyEventListener = new ManageNettyEventListener();
this.remotingServer = new NettyRemotingServer(nettyServerConfig, nettyEventListener, threadPool);
// register processor
this.remotingServer.registerProcessor(ClusterMsg.MessageType.HEARTBEAT, new HeartbeatProcessor(this));
this.remotingServer.registerProcessor(ClusterMsg.MessageType.GO_ONLINE, new CollectorOnlineProcessor(this));
this.remotingServer.registerProcessor(ClusterMsg.MessageType.GO_OFFLINE, new CollectorOfflineProcessor(this));
this.remotingServer.registerProcessor(ClusterMsg.MessageType.RESPONSE_ONE_TIME_TASK_DATA, new CollectOneTimeDataResponseProcessor(this));
this.remotingServer.registerProcessor(ClusterMsg.MessageType.RESPONSE_CYCLIC_TASK_DATA, new CollectCyclicDataResponseProcessor());
this.channelSchedule = Executors.newSingleThreadScheduledExecutor();
}
public void start() {
this.remotingServer.start();
this.channelSchedule.scheduleAtFixedRate(() -> {
try {
this.clientChannelTable.forEach((collector, channel) -> {
if (!channel.isActive()) {
channel.closeFuture();
this.clientChannelTable.remove(collector);
this.collectorAndJobScheduler.collectorGoOffline(collector);
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}, 10, 3, TimeUnit.SECONDS);
}
public void shutdown() {
this.remotingServer.shutdown();
this.channelSchedule.shutdownNow();
}
public CollectorAndJobScheduler getCollectorAndJobScheduler() {
return collectorAndJobScheduler;
}
public Channel getChannel(final String identity) {
Channel channel = this.clientChannelTable.get(identity);
if (channel == null || !channel.isActive()) {
this.clientChannelTable.remove(identity);
log.error("client {} offline now", identity);
}
return channel;
}
public void addChannel(final String identity, Channel channel) {
Channel preChannel = this.clientChannelTable.get(identity);
if (preChannel != null && channel.isActive()) {
preChannel.close();
}
this.clientChannelTable.put(identity, channel);
}
public void closeChannel(final String identity) {
Channel channel = this.getChannel(identity);
if (channel != null) {
this.collectorAndJobScheduler.collectorGoOffline(identity);
ClusterMsg.Message message = ClusterMsg.Message.newBuilder().setType(ClusterMsg.MessageType.GO_CLOSE).build();
this.remotingServer.sendMsg(channel, message);
this.clientChannelTable.remove(identity);
log.info("close collect client success, identity: {}", identity);
}
}
public boolean isChannelExist(final String identity) {
Channel channel = this.clientChannelTable.get(identity);
return channel != null && channel.isActive();
}
public boolean sendMsg(final String identityId, final ClusterMsg.Message message) {
Channel channel = this.getChannel(identityId);
if (channel != null) {
this.remotingServer.sendMsg(channel, message);
return true;
}
return false;
}
public ClusterMsg.Message sendMsgSync(final String identityId, final ClusterMsg.Message message) {<FILL_FUNCTION_BODY>}
@Override
public void run(String... args) throws Exception {
this.start();
}
/**
* manage netty event listener
*/
public class ManageNettyEventListener implements NettyEventListener {
@Override
public void onChannelIdle(Channel channel) {
String identity = null;
for (Map.Entry<String, Channel> entry : ManageServer.this.clientChannelTable.entrySet()) {
if (entry.getValue().equals(channel)) {
identity = entry.getKey();
break;
}
}
if (identity != null) {
ManageServer.this.clientChannelTable.remove(identity);
ManageServer.this.collectorAndJobScheduler.collectorGoOffline(identity);
channel.close();
log.info("handle idle event triggered. the client {} is going offline.", identity);
}
}
}
}
|
Channel channel = this.getChannel(identityId);
if (channel != null) {
return this.remotingServer.sendMsgSync(channel, message, 3000);
}
return null;
| 1,411
| 57
| 1,468
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.