Skip to content

Commit

Permalink
refactor fix potential npe (#1197)
Browse files Browse the repository at this point in the history
Signed-off-by: tomsun28 <tomsun28@outlook.com>
Co-authored-by: Carpe-Wang <wangcarpe@126.com>
Co-authored-by: tomsun28 <tomsun28@outlook.com>
  • Loading branch information
3 people authored Aug 22, 2023
1 parent 5e93a85 commit fc9cca5
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public class AlertTemplateUtil {
private static final Pattern PATTERN = Pattern.compile("\\$\\{(\\w+)\\}");

public static String render(String template, Map<String, Object> replaceData) {
if (template == null) {
return null;
}
try {
Matcher matcher = PATTERN.matcher(template);
StringBuffer buffer = new StringBuffer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.dromara.hertzbeat.common.constants.CommonConstants;
import org.dromara.hertzbeat.common.entity.dto.Message;
import org.dromara.hertzbeat.manager.pojo.dto.LoginDto;
import org.dromara.hertzbeat.manager.pojo.dto.RefreshTokenResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand Down Expand Up @@ -102,41 +103,33 @@ public ResponseEntity<Message<Map<String, String>>> authGetToken(@Valid @Request

@GetMapping("/refresh/{refreshToken}")
@Operation(summary = "Use refresh TOKEN to re-acquire TOKEN", description = "使用刷新TOKEN重新获取TOKEN")
public ResponseEntity<Message<Map<String, String>>> refreshToken(
public ResponseEntity<Message<RefreshTokenResponse>> refreshToken(
@Parameter(description = "Refresh TOKEN | 刷新TOKEN", example = "xxx")
@PathVariable("refreshToken") @NotNull final String refreshToken) {
String userId;
boolean isRefresh;
try {
Claims claims = JsonWebTokenUtil.parseJwt(refreshToken);
userId = String.valueOf(claims.getSubject());
isRefresh = claims.get("refresh", Boolean.class);
String userId = String.valueOf(claims.getSubject());
boolean isRefresh = claims.get("refresh", Boolean.class);
if (userId == null || !isRefresh) {
return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "非法的刷新TOKEN"));
}
SurenessAccount account = accountProvider.loadAccount(userId);
if (account == null) {
return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "TOKEN对应的账户不存在"));
}
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(new Message<>(response));
} catch (Exception e) {
log.info(e.getMessage());
Message<Map<String, String>> message = Message.<Map<String, String>>builder().msg("刷新TOKEN过期或错误")
.code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build();
return ResponseEntity.ok(message);
log.error("Exception occurred during token refresh: {}", e.getClass().getName(), e);
return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "刷新TOKEN过期或错误"));
}
if (userId == null || !isRefresh) {
Message<Map<String, String>> message = Message.<Map<String, String>>builder().msg("非法的刷新TOKEN")
.code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build();
return ResponseEntity.ok(message);
}
SurenessAccount account = accountProvider.loadAccount(userId);
if (account == null) {
Message<Map<String, String>> message = Message.<Map<String, String>>builder().msg("TOKEN对应的账户不存在")
.code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build();
return ResponseEntity.ok(message);
}
List<String> roles = account.getOwnRoles();
// Issue TOKEN 签发TOKEN
String issueToken = JsonWebTokenUtil.issueJwt(userId, PERIOD_TIME, roles);
}
private String issueToken(String userId, List<String> roles, long expirationMillis) {
Map<String, Object> customClaimMap = new HashMap<>(1);
customClaimMap.put("refresh", true);
String issueRefresh = JsonWebTokenUtil.issueJwt(userId, PERIOD_TIME << 5, customClaimMap);
Map<String, String> resp = new HashMap<>(2);
resp.put("token", issueToken);
resp.put("refreshToken", issueRefresh);
return ResponseEntity.ok(new Message<>(resp));
return JsonWebTokenUtil.issueJwt(userId, expirationMillis, roles, customClaimMap);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.dromara.hertzbeat.manager.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;


/**
* Refresh Token Response
* @author Carpe-Wang
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "刷新令牌响应")
public class RefreshTokenResponse {
@Schema(title = "Access Token")
private String token;

@Schema(title = "Refresh Token")
private String refreshToken;
}
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,6 @@ public void enableManageMonitors(HashSet<Long> ids) {
.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);
}
Expand Down Expand Up @@ -733,29 +732,37 @@ public void copyMonitors(List<Long> ids) {
}, () -> log.warn("can not find the monitor for id :{}", id));
});
}

@Override
public void updateAppCollectJob(Job job) {
List<Monitor> availableMonitors = monitorDao.findMonitorsByAppEquals(job.getApp()).
stream().filter(monitor -> monitor.getStatus() == CommonConstants.AVAILABLE_CODE)
.collect(Collectors.toList());
stream().filter(monitor -> monitor.getStatus() == CommonConstants.AVAILABLE_CODE)
.collect(Collectors.toList());
if (!availableMonitors.isEmpty()) {
for (Monitor monitor : availableMonitors) {
// 这里暂时是深拷贝处理
Job appDefine = JsonUtil.fromJson(JsonUtil.toJson(job), Job.class);
appDefine.setMonitorId(monitor.getId());
appDefine.setInterval(monitor.getIntervals());
if (monitor == null || appDefine == null) {
continue;
}
if (monitor.getId() != null) {
appDefine.setMonitorId(monitor.getId());
} else {
continue;
}
if (monitor.getIntervals() !=null ) {
appDefine.setInterval(monitor.getIntervals());
} else {
continue;
}
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());
.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);
}
Expand Down

0 comments on commit fc9cca5

Please sign in to comment.