Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[refactor] move code from MonitorsController to MonitorService #2415

Merged
merged 6 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,15 @@
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.hertzbeat.common.entity.dto.Message;
import org.apache.hertzbeat.common.entity.manager.Monitor;
import org.apache.hertzbeat.manager.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -56,10 +47,6 @@
@RequestMapping(path = "/api/monitors", produces = {APPLICATION_JSON_VALUE})
public class MonitorsController {

private static final byte ALL_MONITOR_STATUS = 9;

private static final int TAG_LENGTH = 2;

@Autowired
private MonitorService monitorService;

Expand All @@ -77,79 +64,16 @@ public ResponseEntity<Message<Page<Monitor>>> getMonitors(
@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,
@Parameter(description = "Monitor tag ", example = "env:prod") @RequestParam(required = false) final String tag) {
Specification<Monitor> specification = (root, query, criteriaBuilder) -> {
List<Predicate> andList = new ArrayList<>();
if (ids != null && !ids.isEmpty()) {
CriteriaBuilder.In<Long> inPredicate = criteriaBuilder.in(root.get("id"));
for (long id : ids) {
inPredicate.value(id);
}
andList.add(inPredicate);
}
if (StringUtils.hasText(app)) {
Predicate predicateApp = criteriaBuilder.equal(root.get("app"), app);
andList.add(predicateApp);
}
if (status != null && status >= 0 && status < ALL_MONITOR_STATUS) {
Predicate predicateStatus = criteriaBuilder.equal(root.get("status"), status);
andList.add(predicateStatus);
}

if (StringUtils.hasText(tag)) {
String[] tagArr = tag.split(":");
String tagName = tagArr[0];
ListJoin<Monitor, org.apache.hertzbeat.common.entity.manager.Tag> tagJoin = root
.join(root.getModel()
.getList("tags", org.apache.hertzbeat.common.entity.manager.Tag.class), JoinType.LEFT);
if (tagArr.length == TAG_LENGTH) {
String tagValue = tagArr[1];
andList.add(criteriaBuilder.equal(tagJoin.get("name"), tagName));
andList.add(criteriaBuilder.equal(tagJoin.get("tagValue"), tagValue));
} else {
andList.add(criteriaBuilder.equal(tagJoin.get("name"), tag));
}
}
Predicate[] andPredicates = new Predicate[andList.size()];
Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates));

List<Predicate> orList = new ArrayList<>();
if (StringUtils.hasText(host)) {
Predicate predicateHost = criteriaBuilder.like(root.get("host"), "%" + host + "%");
orList.add(predicateHost);
}
if (StringUtils.hasText(name)) {
Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%");
orList.add(predicateName);
}
Predicate[] orPredicates = new Predicate[orList.size()];
Predicate orPredicate = criteriaBuilder.or(orList.toArray(orPredicates));

if (andPredicates.length == 0 && orPredicates.length == 0) {
return query.where().getRestriction();
} else if (andPredicates.length == 0) {
return orPredicate;
} else if (orPredicates.length == 0) {
return andPredicate;
} else {
return query.where(andPredicate, orPredicate).getRestriction();
}
};
// Pagination is a must
Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort));
PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp);
Page<Monitor> monitorPage = monitorService.getMonitors(specification, pageRequest);
Message<Page<Monitor>> message = Message.success(monitorPage);
return ResponseEntity.ok(message);
Page<Monitor> monitorPage = monitorService.getMonitors(ids, app, name, host, status, sort, order, pageIndex, pageSize, tag);
return ResponseEntity.ok(Message.success(monitorPage));
}

@GetMapping(path = "/{app}")
@Operation(summary = "Filter all acquired monitoring information lists of the specified monitoring type according to the query",
description = "Filter all acquired monitoring information lists of the specified monitoring type according to the query")
public ResponseEntity<Message<List<Monitor>>> getAppMonitors(
@Parameter(description = "en: Monitoring type", example = "linux") @PathVariable(required = false) final String app) {
List<Monitor> monitors = monitorService.getAppMonitors(app);
Message<List<Monitor>> message = Message.success(monitors);
return ResponseEntity.ok(message);
return ResponseEntity.ok(Message.success(monitorService.getAppMonitors(app)));
}


Expand All @@ -162,8 +86,7 @@ public ResponseEntity<Message<Void>> deleteMonitors(
if (ids != null && !ids.isEmpty()) {
monitorService.deleteMonitors(new HashSet<>(ids));
}
Message<Void> message = Message.success();
return ResponseEntity.ok(message);
return ResponseEntity.ok(Message.success());
}

@DeleteMapping("manage")
Expand All @@ -175,8 +98,7 @@ public ResponseEntity<Message<Void>> cancelManageMonitors(
if (ids != null && !ids.isEmpty()) {
monitorService.cancelManageMonitors(new HashSet<>(ids));
}
Message<Void> message = Message.success();
return ResponseEntity.ok(message);
return ResponseEntity.ok(Message.success());
}

@GetMapping("manage")
Expand All @@ -188,8 +110,7 @@ public ResponseEntity<Message<Void>> enableManageMonitors(
if (ids != null && !ids.isEmpty()) {
monitorService.enableManageMonitors(new HashSet<>(ids));
}
Message<Void> message = Message.success();
return ResponseEntity.ok(message);
return ResponseEntity.ok(Message.success());
}

@GetMapping("/export")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
import org.apache.hertzbeat.manager.pojo.dto.MonitorDto;
import org.apache.hertzbeat.manager.support.exception.MonitorDetectException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.multipart.MultipartFile;

/**
Expand Down Expand Up @@ -96,11 +94,19 @@ public interface MonitorService {

/**
* Dynamic conditional query
* @param specification Query conditions
* @param pageRequest Pagination parameters
* @param monitorIds Monitor ID List
* @param app Monitor Type
* @param name Monitor Name support fuzzy query
* @param host Monitor Host support fuzzy query
* @param status Monitor Status 0:no monitor,1:usable,2:disabled,9:all status
* @param sort Sort Field
* @param order Sort mode eg:asc desc
* @param pageIndex List current page
* @param pageSize Number of list pagination
* @param tag Monitor tag
* @return Search Result
*/
Page<Monitor> getMonitors(Specification<Monitor> specification, PageRequest pageRequest);
Page<Monitor> getMonitors(List<Long> monitorIds, String app, String name, String host, Byte status, String sort, String order, int pageIndex, int pageSize, String tag);

/**
* Unmanaged monitoring items in batches according to the monitoring ID list
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,15 @@
package org.apache.hertzbeat.manager.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
Expand Down Expand Up @@ -71,6 +76,7 @@
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
Expand All @@ -95,6 +101,10 @@ public class MonitorServiceImpl implements MonitorService {
public static final String PATTERN_HTTP = "(?i)http://";
public static final String PATTERN_HTTPS = "(?i)https://";

private static final byte ALL_MONITOR_STATUS = 9;

private static final int TAG_LENGTH = 2;

@Autowired
private AppService appService;

Expand Down Expand Up @@ -642,7 +652,67 @@ public MonitorDto getMonitorDto(long id) throws RuntimeException {
}

@Override
public Page<Monitor> getMonitors(Specification<Monitor> specification, PageRequest pageRequest) {
public Page<Monitor> getMonitors(List<Long> monitorIds, String app, String name, String host, Byte status, String sort, String order, int pageIndex, int pageSize, String tag) {
Specification<Monitor> specification = (root, query, criteriaBuilder) -> {
List<Predicate> andList = new ArrayList<>();
if (monitorIds != null && !monitorIds.isEmpty()) {
CriteriaBuilder.In<Long> inPredicate = criteriaBuilder.in(root.get("id"));
for (long id : monitorIds) {
inPredicate.value(id);
}
andList.add(inPredicate);
}
if (StringUtils.hasText(app)) {
Predicate predicateApp = criteriaBuilder.equal(root.get("app"), app);
andList.add(predicateApp);
}
if (status != null && status >= 0 && status < ALL_MONITOR_STATUS) {
Predicate predicateStatus = criteriaBuilder.equal(root.get("status"), status);
andList.add(predicateStatus);
}

if (StringUtils.hasText(tag)) {
String[] tagArr = tag.split(":");
String tagName = tagArr[0];
ListJoin<Monitor, Tag> tagJoin = root
.join(root.getModel()
.getList("tags", org.apache.hertzbeat.common.entity.manager.Tag.class), JoinType.LEFT);
if (tagArr.length == TAG_LENGTH) {
String tagValue = tagArr[1];
andList.add(criteriaBuilder.equal(tagJoin.get("name"), tagName));
andList.add(criteriaBuilder.equal(tagJoin.get("tagValue"), tagValue));
} else {
andList.add(criteriaBuilder.equal(tagJoin.get("name"), tag));
}
}
Predicate[] andPredicates = new Predicate[andList.size()];
Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates));

List<Predicate> orList = new ArrayList<>();
if (StringUtils.hasText(host)) {
Predicate predicateHost = criteriaBuilder.like(root.get("host"), "%" + host + "%");
orList.add(predicateHost);
}
if (StringUtils.hasText(name)) {
Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%");
orList.add(predicateName);
}
Predicate[] orPredicates = new Predicate[orList.size()];
Predicate orPredicate = criteriaBuilder.or(orList.toArray(orPredicates));

if (andPredicates.length == 0 && orPredicates.length == 0) {
return query.where().getRestriction();
} else if (andPredicates.length == 0) {
return orPredicate;
} else if (orPredicates.length == 0) {
return andPredicate;
} else {
return query.where(andPredicate, orPredicate).getRestriction();
}
};
// Pagination is a must
Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort));
PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp);
return monitorDao.findAll(specification, pageRequest);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -652,9 +653,8 @@ void getMonitorDto() {

@Test
void getMonitors() {
Specification<Monitor> specification = mock(Specification.class);
when(monitorDao.findAll(specification, PageRequest.of(1, 1))).thenReturn(Page.empty());
assertNotNull(monitorService.getMonitors(specification, PageRequest.of(1, 1)));
doReturn(Page.empty()).when(monitorDao).findAll(any(Specification.class), any(PageRequest.class));
assertNotNull(monitorService.getMonitors(null, null, null, null, null, "gmtCreate", "desc", 1, 1, null));
}

@Test
Expand Down
Loading