Commit 43111fd2 authored by cwk's avatar cwk

init

parents
Pipeline #89 failed with stages
/mvnw text eol=lf
*.cmd text eol=crlf
This diff is collapsed.
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hpcner</groupId>
<artifactId>StatusManageService</artifactId>
<version>1.0.0</version>
<name>StatusManageService</name>
<description>StatusManageService</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2024.0.1</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<!-- <optional>true</optional>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.12</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version> <!-- 或其他版本 -->
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-compiler-plugin</artifactId>-->
<!-- <configuration>-->
<!-- <annotationProcessorPaths>-->
<!-- <path>-->
<!-- <groupId>org.projectlombok</groupId>-->
<!-- <artifactId>lombok</artifactId>-->
<!-- </path>-->
<!-- </annotationProcessorPaths>-->
<!-- </configuration>-->
<!-- </plugin>-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.hpcner.statusmanageservice;
import com.hpcner.statusmanageservice.config.ServiceConfig;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
@MapperScan("com.hpcner.statusmanageservice.dao.mapper")
@EnableConfigurationProperties(ServiceConfig.class)
@EnableDiscoveryClient
public class StatusManageServiceApplication {
public static void main(String[] args) {
SpringApplication.run(StatusManageServiceApplication.class, args);
}
}
package com.hpcner.statusmanageservice.bean;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
@Builder
@Data
public class Response {
private Integer code;
private String msg;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Builder.Default
private Date nowTime = new Date();
private Object data;
}
package com.hpcner.statusmanageservice.bean.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import lombok.Data;
import lombok.ToString;
@ToString
@Data
public class EventInfoDTO {
@JsonProperty("type")
private String type;
@JsonProperty("event_name")
private String eventName;
@JsonProperty("event_longitude")
private String eventLongitude;
@JsonProperty("event_latitude")
private String eventLatitude;
@JsonProperty("event_description")
private String eventDescription;
public static EventInfo from(EventInfoDTO eventInfoDTO) {
EventInfo dto = new EventInfo();
dto.setEventName(eventInfoDTO.getEventName());
if(eventInfoDTO.getEventLatitude()!=null && !eventInfoDTO.getEventLatitude().equals("")){
dto.setEventLongitude(Double.parseDouble(eventInfoDTO.getEventLongitude()));
}
if(eventInfoDTO.getEventLatitude()!=null && !eventInfoDTO.getEventLatitude().equals("")){
dto.setEventLatitude(Double.parseDouble(eventInfoDTO.getEventLatitude()));
}
dto.setEventDescription(eventInfoDTO.getEventDescription());
return dto;
}
}
package com.hpcner.statusmanageservice.bean.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.ToString;
@ToString
@Data
public class ServiceInfoDTO {
@JsonProperty("service_operation")
public String serviceOperation;
@JsonProperty("service_type")
public String serviceType;
@JsonProperty("service_id")
public String serviceId;
@JsonProperty("service_name")
public String serviceName;
@JsonProperty("service_state")
public Boolean serviceState;
@JsonProperty("service_json")
public String serviceJson;
}
package com.hpcner.statusmanageservice.bean.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("event_info")
public class EventInfo {
@TableId(value = "event_id", type = IdType.AUTO) // 假设主键自增
@JsonIgnore
private Integer eventId;
/**
* 事件名称
*/
@TableField("event_name")
private String eventName="";
/**
* 事件经度
*/
@TableField("event_longitude")
private Double eventLongitude;
/**
* 事件纬度
*/
@TableField("event_latitude")
private Double eventLatitude;
/**
* 事件描述
*/
@TableField("event_description")
private String eventDescription;
/**
* 是否为当前激活事件
* (使用 Boolean 类型映射 tinyint(1))
*/
@TableField(value = "activate", insertStrategy = FieldStrategy.DEFAULT)
@JsonIgnore
private Boolean activate=false;
@TableField(value = "gmt_create") // 插入时自动填充
@JsonIgnore
private String gmtCreate;
@TableField(value = "gmt_modified") // 更新时自动填充
@JsonIgnore
private String gmtModified;
}
\ No newline at end of file
package com.hpcner.statusmanageservice.bean.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.hpcner.statusmanageservice.bean.dto.ServiceInfoDTO;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("service_info")
public class ServiceInfo {
// -------------------- 主键字段 --------------------
/**
* 服务ID
*/
@TableId(value = "service_id", type = IdType.INPUT)
private String serviceId;
/**
* 服务类型
*/
@TableField(value = "service_type")
private String serviceType;
// -------------------- 其他字段 --------------------
/**
* ID
*/
private Integer id;
/**
* 服务名称
*/
@TableField("service_name")
private String serviceName;
/**
* 服务状态
*/
@TableField("service_state")
private Boolean serviceState;
/**
* 服务JSON配置
*/
@TableField("service_json")
private String serviceJson;
public static ServiceInfo from(ServiceInfoDTO serviceInfoDTO){
if(serviceInfoDTO == null)
{
return null;
}
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(serviceInfoDTO.getServiceId());
serviceInfo.setServiceType(serviceInfoDTO.getServiceType());
serviceInfo.setServiceName(serviceInfoDTO.getServiceName());
serviceInfo.setServiceState(serviceInfoDTO.getServiceState());
serviceInfo.setServiceJson(serviceInfoDTO.getServiceJson());
return serviceInfo;
}
}
package com.hpcner.statusmanageservice.bean.vo;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import lombok.Data;
@Data
public class EventInfoVO {
@JsonProperty("event_name")
private String eventName;
@JsonProperty("event_longitude")
private String eventLongitude;
@JsonProperty("event_latitude")
private String eventLatitude;
@JsonProperty("event_description")
private String eventDescription;
public static EventInfoVO from(EventInfo eventInfo){
if(eventInfo==null){
return null;
}
EventInfoVO vo = new EventInfoVO();
vo.setEventName(eventInfo.getEventName());
if(eventInfo.getEventLongitude()!=null){
vo.setEventLongitude(String.valueOf(eventInfo.getEventLongitude()));
}
if(eventInfo.getEventLatitude()!=null){
vo.setEventLatitude(String.valueOf(eventInfo.getEventLatitude()));
}
vo.setEventDescription(eventInfo.getEventDescription());
return vo;
}
}
package com.hpcner.statusmanageservice.bean.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import lombok.Data;
@Data
public class ServiceInfoVO {
@JsonProperty("service_state")
private String serviceState;
@JsonProperty("service_id")
private String serviceId;
@JsonProperty("service_name")
private String serviceName;
@JsonProperty("service_json")
private String serviceJson;
public static ServiceInfoVO from(ServiceInfo serviceInfo){
if(serviceInfo==null){
return null;
}
ServiceInfoVO vo = new ServiceInfoVO();
if(serviceInfo.getServiceState())
{
vo.setServiceState("run");
}else {
vo.setServiceState("stop");
}
vo.setServiceId(serviceInfo.getServiceId());
vo.setServiceName(serviceInfo.getServiceName());
vo.setServiceJson(serviceInfo.getServiceJson());
return vo;
}
}
package com.hpcner.statusmanageservice.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
public class AppConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.hpcner.statusmanageservice.config;
import com.hpcner.statusmanageservice.serv.BaseService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@ConfigurationProperties(prefix = "service-config")
@Data
@Component
public class ServiceConfig {
public List<BaseService> recogLists;
public List<BaseService> deployLists;
public List<BaseService> otherLists;
}
package com.hpcner.statusmanageservice.constant;
public class ResponseConstant {
public static Integer RES_OK = 200; // 响应正常,且有值可以返回
public static Integer RES_NO_DATA = 201; // 响应正常,但无数据
public static Integer RES_NEED_CHECK = 400; // 表示未被以下错误码分类的未知错误,msg中需要附加错误的简要信息,详细情况需要检查日志
// 注:如果是经常发生的错误/异常,建议在下面新建常量
public static Integer RES_ILLEGAL_PARAM = 401; // 非法参数
public static Integer RES_ILLEGAL_ACTION = 402; // 非法操作,比如某些操作的前置条件不满足。
public static Integer RES_TOO_MANY_REQUESTS = 403; // 前端请求过于频繁。注:一般发生于线程池饱和的时候,捕捉线程池的相关异常
public static Integer RES_RESOURCES_OUT = 404; // 资源耗尽。注:一般发生于线程池饱和的时候,捕捉线程池的相关异常
public static Integer RES_ALGO_NO_RUN = 451; // 该算法状态(runningStatus)为 False,请先修改算法状态
public static Integer RES_ALGO_NO_CONN = 452; // 无法建立与算法层的连接,需要检查算法是否启动。同步调用
public static Integer RES_ALGO_TIMEOUT = 453; // 算法层响应超时,需要检查算法是否存在问题。同步调用
public static Integer RES_SERVER_ERROR = 500; // 服务器错误或异常,需要检查日志,进行异常的标注
// 其实这个状态码用不到,真正发生服务器异常的时候返回的应该是http状态码500了
}
\ No newline at end of file
package com.hpcner.statusmanageservice.controller;
import com.hpcner.statusmanageservice.bean.Response;
import com.hpcner.statusmanageservice.bean.dto.EventInfoDTO;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import com.hpcner.statusmanageservice.bean.vo.EventInfoVO;
import com.hpcner.statusmanageservice.constant.ResponseConstant;
import com.hpcner.statusmanageservice.service.database.EventInfoService;
import com.hpcner.statusmanageservice.utils.TimeUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import java.util.Map;
@Slf4j
@Controller
@RequestMapping("/event")
public class EventController {
@Resource
private EventInfoService eventInfoService;
@PostMapping("/manage")
@ResponseBody
public Response manageEvent(@RequestBody EventInfoDTO eventInfoDTO) {
try {
log.info("Event Action: {}", eventInfoDTO);
if(eventInfoDTO == null){
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("非法参数").data("").build();
}
if(eventInfoDTO.getType()==null){
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("非法参数").data("").build();
}
String action = eventInfoDTO.getType().toLowerCase();
boolean success = false;
EventInfo eventInfo = EventInfoDTO.from(eventInfoDTO);
if(action.equals("update")){
success = eventInfoService.UpdateEventByName(eventInfo);
}else if(action.equals("delete")) {
success = eventInfoService.DeleteEventByName(eventInfo);
}else if(action.equals("insert")){
int inserted = eventInfoService.InsertEventByName(eventInfo);
if(inserted == -1){
success = false;
return Response.builder().code(500).msg("事件已存在").data("").build();
}else{
success=true;
}
}else if(action.equals("set")){
success = eventInfoService.ActivateByName(eventInfo);
}
else if(action.equals("unset")){
success = eventInfoService.DeactivateByName(eventInfo);
}
if(success){
return Response.builder().code(ResponseConstant.RES_OK).msg("成功更新配置信息!").data("").build();
}else{
return Response.builder().code(500).msg("请检查").data("").build();
}
}catch (Exception e){
log.error("Error occurred while managing event: {}", e.getMessage());
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("服务器错误,请查看日志").data(e.getMessage()).build();
}
}
@PostMapping("/info")
@ResponseBody
public Response manageEvent(){
try {
List<EventInfo> eventInfo = eventInfoService.GetAllEventInfo();
List<EventInfoVO> eventInfoVO = new ArrayList<>();
if(eventInfo!=null) {
for(EventInfo eventInfoVO1 : eventInfo){
eventInfoVO.add(EventInfoVO.from(eventInfoVO1));
}
}
EventInfo activateEvent = eventInfoService.GetActivate();
Map<String,Object> ret = new java.util.Hashtable<>();
if(activateEvent!=null)
ret.put("current_event",activateEvent.getEventName());
else
ret.put("current_event","null");
ret.put("event_list",eventInfoVO);
return Response.builder().code(ResponseConstant.RES_OK).msg("成功获取事件信息").data(ret).build();
}catch (Exception e){
log.error("Error occurred while managing event: {}", e.getMessage());
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("服务器错误,请查看日志").data(e.getMessage()).build();
}
}
}
package com.hpcner.statusmanageservice.controller;
import com.hpcner.statusmanageservice.bean.Response;
import com.hpcner.statusmanageservice.bean.dto.ServiceInfoDTO;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.bean.vo.ServiceInfoVO;
import com.hpcner.statusmanageservice.constant.ResponseConstant;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.serv.ServiceFactory;
import com.hpcner.statusmanageservice.service.database.ServiceInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Controller
@RequestMapping("/service")
public class ServiceController {
@Resource
private ServiceInfoService serviceInfoService;
@PostMapping("/manage")
@ResponseBody
public Response manageService(@RequestBody ServiceInfoDTO serviceInfoDTO){
try {
if (serviceInfoDTO == null || serviceInfoDTO.serviceType == null || serviceInfoDTO.serviceId == null) {
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("非法参数").data("").build();
}
String action = serviceInfoDTO.serviceOperation.toLowerCase();
boolean success = false;
// ServiceInfo serviceInfo = ServiceInfo.from(serviceInfoDTO);
BaseService baseService = ServiceFactory.CreateService(serviceInfoDTO);
if(baseService==null) {
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("找不到服务").data("").build();
}
if (action.equals("start")) {
if(!serviceInfoService.IsActivate(serviceInfoDTO.serviceId)) {
success = baseService.start(serviceInfoDTO.serviceJson);
}else{
return Response.builder().code(ResponseConstant.RES_ILLEGAL_ACTION).msg("服务已启动").data("").build();
}
} else if (action.equals("stop")) {
if(!serviceInfoService.IsActivate(serviceInfoDTO.serviceId)) {
return Response.builder().code(ResponseConstant.RES_ILLEGAL_ACTION).msg("服务已停止").data("").build();
}
success = baseService.stop();
} else if (action.equals("restart")) {
success = baseService.restart(serviceInfoDTO.serviceJson);
}
if (!success) {
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("操作失败").data("").build();
}
return Response.builder().code(ResponseConstant.RES_OK).msg("成功更新配置信息!").data("").build();
}catch (NotFoundException e) {
return Response.builder().code(ResponseConstant.RES_ILLEGAL_ACTION).msg("服务未找到").data("").build();
}
catch (Exception e){
log.error("Error in updateService: {}", e.getMessage());
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("服务器错误").data("").build();
}
}
@PostMapping("/update")
@ResponseBody
public Response updateService(@RequestBody ServiceInfoDTO serviceInfoDTO){
try {
if (serviceInfoDTO == null || serviceInfoDTO.serviceId == null) {
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("非法参数").data("").build();
}
log.info("Service Update {}",serviceInfoDTO);
boolean success = serviceInfoService.UpsertServiceInfoByServiceId(ServiceInfo.from(serviceInfoDTO));
if (!success) {
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("更新失败").data("").build();
}
return Response.builder().code(ResponseConstant.RES_OK).msg("成功更新配置信息!").data("").build();
}catch (Exception e){
log.error("Error in updateService: {}", e.getMessage());
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("服务器错误").data("").build();
}
}
@PostMapping("/info")
@ResponseBody
public Response getServiceInfo( ) {
try {
List<ServiceInfo> serviceInfos = serviceInfoService.ListAll();
Map<String,List<ServiceInfoVO>> ret = new HashMap<>();
ret.put("other",new ArrayList<>());
ret.put("deploy",new ArrayList<>());
ret.put("recog",new ArrayList<>());
if (serviceInfos == null || serviceInfos.isEmpty()) {
return Response.builder().code(ResponseConstant.RES_OK).msg("成功获取服务信息!").data(ret).build();
}
for (ServiceInfo serviceInfo : serviceInfos) {
String serviceType = serviceInfo.getServiceType();
ret.get(serviceType).add(ServiceInfoVO.from(serviceInfo));
}
return Response.builder().code(ResponseConstant.RES_OK).msg("成功获取服务信息!").data(ret).build();
} catch (Exception e) {
log.error("Error in getServiceInfo: {}", e.getMessage());
return Response.builder().code(ResponseConstant.RES_SERVER_ERROR).msg("服务器错误").data("").build();
}
}
}
package com.hpcner.statusmanageservice.controller;
import com.hpcner.statusmanageservice.bean.Response;
import com.hpcner.statusmanageservice.constant.ResponseConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
@Controller
@Slf4j
public class StaticPageController {
Logger logger = (Logger) LoggerFactory.getLogger("com.hpcner");
private final Map<String,Level> levelMap = Map.of(
"DEBUG",Level.DEBUG,
"INFO",Level.INFO,
"WARN",Level.WARN,
"ERROR",Level.ERROR,
"TRACE",Level.TRACE,
"ALL",Level.ALL,
"OFF",Level.OFF
);
/**
* 注意,这里是个静态映射,返回的是一个html页面
* 该页面内容位于 src/main/resources/static/index.html
* 当访问"/" 或者 "index.html"时都会返回此html页面的内容
* 具体内容可见:
* <a href="https://blog.csdn.net/Blue_Zwj/article/details/123312856">...</a>
* <a href="https://www.jb51.net/article/195744.htm">...</a>
* <a href="https://blog.csdn.net/m0_67391870/article/details/124469402">...</a>
* 静态映射时不能加 @RestController 或者 @ResponseBody 注解。
* @return index.html页面内容
*/
@GetMapping("/")
public String index(){
return "index";
}
@RequestMapping(value = "/",method = {RequestMethod.HEAD})
@ResponseBody
public Response healthCheck() {
//aliyun slb health check
log.debug("health check");
return Response.builder().code(200).msg("ok").data("").build();
}
@GetMapping("/v3/")
public String indexV3(){
return "index";
}
@PostMapping("/loglevel")
@ResponseBody
public Response changeLogLevel(@RequestParam("level") String level){
String levelUpperCase = level.toUpperCase();
if(levelMap.containsKey(levelUpperCase)){
logger.setLevel(levelMap.get(levelUpperCase));
return Response.builder().code(200).msg(String.format("日志等级修改为%s",levelUpperCase)).data("").build();
}
return Response.builder().code(ResponseConstant.RES_ILLEGAL_PARAM).msg("非法参数").data("").build();
}
}
package com.hpcner.statusmanageservice.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
public interface EventInfoMapper extends BaseMapper<EventInfo> {
}
package com.hpcner.statusmanageservice.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
public interface ServiceInfoMapper extends BaseMapper<ServiceInfo> {
}
package com.hpcner.statusmanageservice.serv;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
@ToString
@Data
@Slf4j
public class BaseService {
String id;
String name;
//String json;
public boolean start(String json) throws JsonProcessingException {
return false;
}
public boolean stop() throws JsonProcessingException {
return false;
}
public boolean restart(String json) throws JsonProcessingException {
return false;
}
public void reValue(BaseService other){
id = other.getId();
name = other.getName();
//json = other.getJson();
}
}
package com.hpcner.statusmanageservice.serv;
import com.hpcner.statusmanageservice.bean.dto.ServiceInfoDTO;
import com.hpcner.statusmanageservice.serv.deploy.DeployService;
import java.util.HashMap;
import java.util.Map;
public class ServiceFactory {
static {
// Initialize the serviceMap with the appropriate services
serviceMap = new HashMap<>();
}
public static Map<String,Map<String,BaseService>> serviceMap;
public static BaseService CreateService(ServiceInfoDTO serviceInfo) {
String type = serviceInfo.getServiceType().toLowerCase();
if(serviceMap.containsKey(type)){
Map<String,BaseService> sm = serviceMap.get(type);
if(sm.containsKey(serviceInfo.getServiceId())) {
return sm.get(serviceInfo.getServiceId());
}
}
return null;
}
}
package com.hpcner.statusmanageservice.serv.deploy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component("deploy_empty")
public class DeployEmptyService extends DeployService{
}
package com.hpcner.statusmanageservice.serv.deploy;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hpcner.statusmanageservice.constant.ResponseConstant;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.utils.ApplicationContextUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Slf4j
@Data
public class DeployService extends BaseService {
public static final String BASE_URL="http://iccs-b-server24-2";
@Override
public boolean start(String json) throws JsonProcessingException {
RestTemplate restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
String url = BASE_URL + "/algo/control/run";
Map<String,Object> req = Map.of(
"algo_name", getId()
);
ResponseEntity<String> result = restTemplate.postForEntity(url, req, String.class);
if(result.getStatusCode().equals(HttpStatus.OK)){
String retBody = result.getBody();
log.info("DeployService start result: {}", retBody);
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObject = mapper.readTree(retBody);
if(!jsonObject.has("code")){
log.info("Error parse deploy result: {}", retBody);
return false;
}else{
if(jsonObject.get("code").asInt()!= ResponseConstant.RES_OK){
log.info("Error starting deploy: {}", jsonObject.get("msg").asText());
return false;
}
}
return true;
}else{
return false;
}
}
@Override
public boolean stop() throws JsonProcessingException {
RestTemplate restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
String url = BASE_URL + "/algo/control/stop";
Map<String,Object> req = Map.of(
"algo_name", getId()
);
ResponseEntity<String> result = restTemplate.postForEntity(url, req, String.class);
if(result.getStatusCode().equals(HttpStatus.OK)){
String retBody = result.getBody();
log.info("DeployService start result: {}", retBody);
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObject = mapper.readTree(retBody);
if(!jsonObject.has("code")){
log.info("Error parse deploy result: {}", retBody);
return false;
}else{
if(jsonObject.get("code").asInt()!= ResponseConstant.RES_OK){
log.info("Error starting deploy: {}", jsonObject.get("msg").asText());
return false;
}
}
return true;
}else{
return false;
}
}
@Override
public boolean restart(String json) throws JsonProcessingException {
RestTemplate restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
String url = BASE_URL + "/algo/control/restart";
Map<String,Object> req = Map.of(
"algo_name", getId()
);
ResponseEntity<String> result = restTemplate.postForEntity(url, req, String.class);
if(result.getStatusCode().equals(HttpStatus.OK)){
String retBody = result.getBody();
log.info("DeployService start result: {}", retBody);
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObject = mapper.readTree(retBody);
if(!jsonObject.has("code")){
log.info("Error parse deploy result: {}", retBody);
return false;
}else{
if(jsonObject.get("code").asInt()!= ResponseConstant.RES_OK){
log.info("Error starting deploy: {}", jsonObject.get("msg").asText());
return false;
}
}
return true;
}else{
return false;
}
}
}
package com.hpcner.statusmanageservice.serv.deploy;
import org.springframework.stereotype.Component;
@Component("deploy_kmeans_xieyaqi")
public class DeployXyqService extends DeployService{
}
package com.hpcner.statusmanageservice.serv.deploy;
import org.springframework.stereotype.Component;
@Component("deploy_zhangyuhao")
public class DeployZyhService extends DeployService{
}
package com.hpcner.statusmanageservice.serv.deploy;
import org.springframework.stereotype.Component;
@Component("map_wangzao")
public class MapWzService extends DeployService{
}
package com.hpcner.statusmanageservice.serv.other;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.service.database.ServiceInfoService;
import com.hpcner.statusmanageservice.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component("other_simulator")
@Slf4j
public class SimulatorService extends BaseService {
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/start
//{"network":"network started (PID: 13791)","person":"person started (PID: 13792)","uav":"uav started (PID: 13793)"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/start
//{"network":"network already running","person":"person already running","uav":"uav already running"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/stop
//{"network":"network stopped","person":"person stopped","uav":"uav stopped"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/stop
//{"network":"network not running","person":"person not running","uav":"uav not running"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/restart
//{"network":"network started (PID: 13851)","person":"person started (PID: 13852)","uav":"uav started (PID: 13853)"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/restart
//{"network":"network already running","person":"person already running","uav":"uav already running"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/stop
//{"network":"network not running","person":"person not running","uav":"uav not running"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/stop
//{"network":"network not running","person":"person not running","uav":"uav not running"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/start
//{"network":"network started (PID: 13899)","person":"person started (PID: 13900)","uav":"uav started (PID: 13901)"}
//(base) [cwk@iZ2ze2pfzefpro00cn0ybhZ backend-5.1.0]$ curl -X POST http://127.0.0.1:5096/stop
//{"network":"network stopped","person":"person stopped","uav":"uav stopped"}
public static final String BASE_URL="http://localhost:5096";
@Override
public boolean start(String json) {
try {
String url = String.format("%s/start", BASE_URL);
log.info("Start other sim {}", url);
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
String result = restTemplate.postForObject(url, null, String.class);
log.info("other sim result: {}", result);
if (result == null) {
log.info("Error parse other sim result: {}", result);
return false;
}
ObjectMapper mapper = new ObjectMapper();
JsonNode resultObject = mapper.readTree(result);
if (resultObject == null) {
log.info("Error parse other sim result: {}", result);
return false;
}
if (resultObject.has("network")) {
if (!resultObject.get("network").asText().contains("started")) {
return false;
}
}
if (resultObject.has("person")) {
if (!resultObject.get("person").asText().contains("started")) {
return false;
}
}
if (resultObject.has("uav")) {
if (!resultObject.get("uav").asText().contains("started")) {
return false;
}
}
ServiceInfoService serviceInfoService = ApplicationContextUtil.getBean(ServiceInfoService.class);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(getId());
serviceInfo.setServiceState(true);
serviceInfoService.UpsertServiceInfoByServiceId(serviceInfo);
return true;
} catch (Exception e) {
log.error("Exception in other sim", e);
return false;
}
}
@Override
public boolean stop() {
try {
String url = String.format("%s/stop", BASE_URL);
log.info("Stop other sim {}", url);
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
String result = restTemplate.postForObject(url, null, String.class);
log.info("other sim result: {}", result);
if (result == null) {
log.info("Error parse other sim result: {}", result);
return false;
}
ObjectMapper mapper = new ObjectMapper();
JsonNode resultObject = mapper.readTree(result);
if (resultObject == null) {
log.info("Error parse other sim result: {}", result);
return false;
}
if (resultObject.has("network")) {
if (!resultObject.get("network").asText().contains("stopped")) {
return false;
}
}
if (resultObject.has("person")) {
if (!resultObject.get("person").asText().contains("stopped")) {
return false;
}
}
if (resultObject.has("uav")) {
if (!resultObject.get("uav").asText().contains("stopped")) {
return false;
}
}
ServiceInfoService serviceInfoService = ApplicationContextUtil.getBean(ServiceInfoService.class);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(getId());
serviceInfo.setServiceState(false);
serviceInfoService.UpsertServiceInfoByServiceId(serviceInfo);
return true;
} catch (Exception e) {
log.error("Exception in other sim", e);
return false;
}
}
@Override
public boolean restart(String json) {
if(!stop()){
return false;
}
if(start(json)){
return true;
}
else{
return false;
}
}
}
package com.hpcner.statusmanageservice.serv.recog;
import com.hpcner.statusmanageservice.serv.BaseService;
public class RecogService extends BaseService {
}
package com.hpcner.statusmanageservice.serv.recog;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.service.database.ServiceInfoService;
import com.hpcner.statusmanageservice.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Component("recog-zgs")
@Slf4j
public class RecogZgsService extends RecogService{
public static final String BASE_URL="http://localhost:8081";
@Override
public boolean start(String json) {
//curl -X POST "http://localhost:8081/models?url=retinanet.mar&initial_workers=3"
String modelUrl = "retinanet.mar";
int workers = 3;
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObject = mapper.readTree(json);
if (jsonObject.has("url")) {
modelUrl = jsonObject.get("url").asText();
}
if (jsonObject.has("initial_workers")) {
workers = jsonObject.get("initial_workers").asInt();
}
String url = String.format("%s/models?url=%s&initial_workers=%d", BASE_URL, modelUrl, workers);
log.info("Start recog zgs {}", url);
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
String result = restTemplate.postForObject(url, null, String.class);
JsonNode resultObject = mapper.readTree(result);
if (resultObject == null) {
log.info("Error parse recog zgs result: {}", result);
return false;
}
if (resultObject.has("code")) {
log.info("Error starting recog zgs: {}", resultObject.path("message").asText());
return false;
}
ServiceInfoService serviceInfoService = ApplicationContextUtil.getBean(ServiceInfoService.class);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(getId());
serviceInfo.setServiceState(true);
serviceInfoService.UpsertServiceInfoByServiceId(serviceInfo);
return true;
} catch (Exception e) {
log.error("Exception in start recog zgs", e);
return false;
}
}
@Override
public boolean stop() {
String url = String.format("%s/models/retinanet/1.0",BASE_URL);
log.info("Stop recog zgs {}",url);
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
// 发送DELETE请求并获取响应
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.DELETE,
entity,
String.class
);
if(response.getStatusCode().equals(HttpStatus.OK)){
log.info("Stop recog zgs success");
ServiceInfoService serviceInfoService = ApplicationContextUtil.getBean(ServiceInfoService.class);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(getId());
serviceInfo.setServiceState(false);
serviceInfoService.UpsertServiceInfoByServiceId(serviceInfo);
return true;
}
return false;
}
@Override
public boolean restart(String json) {
if(!stop()){
return false;
}
if(start(json)){
return true;
}
else{
return false;
}
}
}
package com.hpcner.statusmanageservice.service.database;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import java.util.List;
public interface EventInfoService extends IService<EventInfo> {
public int InsertEventByName(EventInfo newEvent);
public boolean ActivateByName(EventInfo eventInfo);
public boolean DeactivateByName(EventInfo eventInfo);
public boolean DeleteEventByName(EventInfo eventInfo);
public boolean UpdateEventByName(EventInfo eventInfo);
public EventInfo GetActivate();
public List<EventInfo> GetAllEventInfo();
}
package com.hpcner.statusmanageservice.service.database;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.serv.BaseService;
import org.apache.ibatis.javassist.NotFoundException;
import java.util.List;
import java.util.Map;
public interface ServiceInfoService extends IService<ServiceInfo> {
public ServiceInfo GetServiceInfoByServiceId(String sid);
public boolean UpsertServiceInfoByServiceId(ServiceInfo serviceInfo);
public boolean DeleteServiceInfoByServiceId(String sid);
public List<ServiceInfo> ListAll();
public void DeleteNotExist(Map<String, Map<String, BaseService>> info);
public boolean IsActivate(String sid) throws NotFoundException;
}
package com.hpcner.statusmanageservice.service.database.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import com.hpcner.statusmanageservice.dao.mapper.EventInfoMapper;
import com.hpcner.statusmanageservice.service.database.EventInfoService;
import com.hpcner.statusmanageservice.utils.TimeUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Slf4j
public class EventInfoServiceImpl extends ServiceImpl<EventInfoMapper, EventInfo> implements EventInfoService {
@Override
public int InsertEventByName(EventInfo newEvent) {
if(newEvent == null || newEvent.getEventName() == null|| newEvent.getEventName().equals("")){
return -1;
}
QueryWrapper<EventInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("event_name", newEvent.getEventName());
EventInfo eventInfo = this.getOne(queryWrapper);
if (eventInfo != null) {
return -1;
}
newEvent.setGmtCreate(TimeUtils.getNowTime());
newEvent.setGmtModified(TimeUtils.getNowTime());
this.save(newEvent);
QueryWrapper<EventInfo> queryWrapper2 = new QueryWrapper<>();
queryWrapper2.eq("event_name",newEvent.getEventName());
eventInfo = this.getOne(queryWrapper2);
if(eventInfo==null){
log.info("Can't find {}",newEvent.getEventName());
return 0;
}
return eventInfo.getEventId();
}
@Override
public boolean ActivateByName(EventInfo eventInfo) {
if(eventInfo == null || eventInfo.getEventName() == null|| eventInfo.getEventName().equals("")){
return false;
}
UpdateWrapper<EventInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("activate",false);
this.update(updateWrapper);
updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("event_name", eventInfo.getEventName());
updateWrapper.set("activate",true).set("gmt_modified", TimeUtils.getNowTime());
return this.update(updateWrapper);
}
@Override
public boolean DeactivateByName(EventInfo eventInfo) {
if(eventInfo == null || eventInfo.getEventName() == null|| eventInfo.getEventName().equals("")){
return false;
}
UpdateWrapper<EventInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("event_name", eventInfo.getEventName());
updateWrapper.set("activate",false).set("gmt_modified", TimeUtils.getNowTime());
return this.update(updateWrapper);
}
@Override
public boolean DeleteEventByName(EventInfo eventInfo) {
if(eventInfo == null || eventInfo.getEventName() == null|| eventInfo.getEventName().equals("")){
return false;
}
QueryWrapper<EventInfo> queryWrapper = Wrappers.query();
queryWrapper.eq("event_name", eventInfo.getEventName());
return this.remove(queryWrapper);
}
@Override
public boolean UpdateEventByName(EventInfo eventInfo) {
if (eventInfo == null || eventInfo.getEventName() == null || eventInfo.getEventName().equals("")) {
return false;
}
UpdateWrapper<EventInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("event_name", eventInfo.getEventName());
if (eventInfo.getEventLongitude() != null) {
updateWrapper.set("event_longitude", eventInfo.getEventLongitude());
}
if (eventInfo.getEventLatitude() != null) {
updateWrapper.set("event_latitude", eventInfo.getEventLatitude());
}
if (eventInfo.getEventDescription() != null) {
updateWrapper.set("event_description", eventInfo.getEventDescription());
}
updateWrapper.set("gmt_modified", TimeUtils.getNowTime());
return this.update(updateWrapper);
}
@Override
public EventInfo GetActivate() {
QueryWrapper<EventInfo> queryWrapper = Wrappers.query();
queryWrapper.eq("activate", true);
EventInfo eventInfo = this.getOne(queryWrapper);
if (eventInfo == null || eventInfo.getEventName() == null || eventInfo.getEventName().equals("")) {
return null ;
}
return eventInfo;
}
@Override
public List<EventInfo> GetAllEventInfo() {
List<EventInfo> eventInfos = this.list();
if (eventInfos == null || eventInfos.isEmpty()) {
return null;
}
for (EventInfo eventInfo : eventInfos) {
if (eventInfo.getGmtCreate() == null || eventInfo.getGmtModified() == null) {
return null;
}
}
return eventInfos;
}
}
package com.hpcner.statusmanageservice.service.database.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.dao.mapper.ServiceInfoMapper;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.service.database.ServiceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Slf4j
@Repository
public class ServiceInfoServiceImpl extends ServiceImpl<ServiceInfoMapper, ServiceInfo> implements ServiceInfoService {
public static final String key = "service_id";
@Override
public ServiceInfo GetServiceInfoByServiceId(String sid) {
QueryWrapper<ServiceInfo> queryWrapper = Wrappers.query();
queryWrapper.eq(key,sid);
return this.getOne(queryWrapper);
}
@Override
public boolean UpsertServiceInfoByServiceId(ServiceInfo serviceInfo) {
if(serviceInfo == null || serviceInfo.getServiceId() ==null){
return false;
}
QueryWrapper<ServiceInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(key,serviceInfo.getServiceId());
ServiceInfo existingServiceInfo = this.getOne(queryWrapper);
if (existingServiceInfo == null) {
if(serviceInfo.getServiceType()==null){
serviceInfo.setServiceType("other");
}
return this.save(serviceInfo);
}
UpdateWrapper<ServiceInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq(key,serviceInfo.getServiceId());
if(serviceInfo.getServiceState()!=null){
updateWrapper.set("service_state",serviceInfo.getServiceState());
}
if(serviceInfo.getServiceJson()!=null){
updateWrapper.set("service_json",serviceInfo.getServiceJson());
}
if(serviceInfo.getServiceName()!=null){
updateWrapper.set("service_name",serviceInfo.getServiceName());
}
if(serviceInfo.getServiceType()!=null){
updateWrapper.set("service_type",serviceInfo.getServiceType());
}
return this.update(updateWrapper);
}
@Override
public boolean DeleteServiceInfoByServiceId(String sid) {
if(sid == null ){
return false;
}
return this.remove(Wrappers.<ServiceInfo>query().eq(key,sid));
}
@Override
public List<ServiceInfo> ListAll() {
return this.list();
}
@Override
public void DeleteNotExist(Map<String, Map<String, BaseService>> info) {
List<ServiceInfo> serviceInfos = this.list();
for (ServiceInfo serviceInfo : serviceInfos) {
String serviceId = serviceInfo.getServiceId();
String serviceType = serviceInfo.getServiceType();
Map<String, BaseService> services = info.get(serviceType);
if (services == null || !services.containsKey(serviceId)) {
this.DeleteServiceInfoByServiceId(serviceId);
}
}
}
@Override
public boolean IsActivate(String sid) throws NotFoundException {
if(sid == null){
throw new NotFoundException("Service id is null");
}
QueryWrapper<ServiceInfo> queryWrapper = Wrappers.query();
queryWrapper.eq(key,sid);
ServiceInfo serviceInfo = this.getOne(queryWrapper);
if(serviceInfo == null){
throw new NotFoundException("Service not found");
}
return serviceInfo.getServiceState();
}
}
package com.hpcner.statusmanageservice.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
@Slf4j
//@Deprecated
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return context;
}
/**
* 通过name获取 Bean
*
* @param name beanName
* @return Object
*/
public static Object getBean(String name){
log.debug("Bean "+name+" getting");
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> requiredType) throws BeansException{
if (requiredType!=null) {
log.debug("Bean " +requiredType.toString()+ " getting");
}
return getApplicationContext().getBean(requiredType);
}
}
package com.hpcner.statusmanageservice.utils;
import com.hpcner.statusmanageservice.bean.entity.ServiceInfo;
import com.hpcner.statusmanageservice.config.ServiceConfig;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.serv.ServiceFactory;
import com.hpcner.statusmanageservice.service.database.ServiceInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class InitHelper implements CommandLineRunner {
@Resource
private ServiceConfig serviceConfig;
@Resource
private ServiceInfoService serviceInfoService;
@Override
public void run(String... args) throws Exception {
Map<String, Map<String, BaseService>> serviceMap = ServiceFactory.serviceMap;
List<BaseService> deployLists = serviceConfig.getDeployLists();
Map<String,BaseService> deployMap = new HashMap<>();
for (BaseService deploy : deployLists) {
BaseService bean =(BaseService) ApplicationContextUtil.getBean(deploy.getId());
if (bean != null) {
bean.reValue(deploy);
log.info("Deploy bean: {}", bean.getId());
deployMap.put(deploy.getId(), bean);
}
}
serviceMap.put("deploy", deployMap);
List<BaseService> recogLists = serviceConfig.getRecogLists();
Map<String,BaseService> recogMap = new HashMap<>();
for (BaseService recog : recogLists) {
BaseService bean =(BaseService) ApplicationContextUtil.getBean(recog.getId());
if (bean != null) {
bean.reValue(recog);
log.info("Recog bean: {}", bean.getId());
recogMap.put(recog.getId(), bean);
}
}
serviceMap.put("recog", recogMap);
List<BaseService> otherLists = serviceConfig.getOtherLists();
Map<String,BaseService> otherMap = new HashMap<>();
for (BaseService other : otherLists) {
BaseService bean =(BaseService) ApplicationContextUtil.getBean(other.getId());
if (bean != null) {
bean.reValue(other);
log.info("Other bean: {}", bean.getId());
otherMap.put(other.getId(), bean);
}
}
serviceMap.put("other", otherMap);
log.info("Service map initialized: {}", serviceMap);
// 初始化服务信息
for (Map.Entry<String, Map<String, BaseService>> entry : serviceMap.entrySet()) {
String serviceType = entry.getKey();
Map<String, BaseService> services = entry.getValue();
for (Map.Entry<String, BaseService> serviceEntry : services.entrySet()) {
BaseService service = serviceEntry.getValue();
ServiceInfo si = new ServiceInfo();
si.setServiceId(service.getId());
si.setServiceName(service.getName());
si.setServiceType(serviceType);
//si.setServiceJson(service.getJson());
serviceInfoService.UpsertServiceInfoByServiceId(si);
}
}
serviceInfoService.DeleteNotExist(serviceMap);
}
}
package com.hpcner.statusmanageservice.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeUtils {
/**
* 获取当前时间,格式为("yyyy-MM-dd HH:mm:ss")
* @return 当前时间,字符串形式
*/
public static String getNowTime(){
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime = dateformat.format(new Date());
return nowTime;
}
/**
* TODO 代码逻辑还没写
* 检查时间字符串是否能转为时间类型以及是否符合约定的格式
* @return true,表示可转且符合;false,表示不可转或者不符合
*/
public static boolean checkTimeValid(){
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String nowTime = dateformat.format(new Date());
return true;
}
}
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
spring.boot.admin.client.instance.service-url=http://127.0.0.1:13456/
spring.boot.admin.client.instance.name=StatusManageService
\ No newline at end of file
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# default-property-inclusion: non_null # JSON处理时忽略非空字段
mvc:
view:
prefix: /
suffix: .html
datasource:
url: jdbc:mysql://rm-2zeb9i9459mu4i1f19o.mysql.rds.aliyuncs.com:3306/iccs_scene_deploy?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
username: iccs_scene_deploy
password: iccs_scene_deploy_1209
driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://127.0.0.1:3306/iccs_scene_deploy?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
# username: cwk
# password: 123
#DatabaseServiceImpl中对应的数据库也要改
application:
name: StatusManageService
cloud:
consul:
host: localhost
port: 8500
discovery:
register: true
prefer-ip-address: true
mybatis-plus:
#type-aliases-package: com.hpcn.entity # 别名扫描包
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: auto
enable-sql-runner: true
logging:
level:
com.hpcner: info
#com.hpcn: info
# 更改tomcat的web端口号,本模块使用老师规定的端口号:9002
server:
port: 13456
service-config:
recog-lists:
- id: recog-zgs
name: 张高帅算法
#json: "{ \"url\":\"String\",\"initial_workers\":\"Integer\" }"
deploy-lists:
- id: deploy_zhangyuhao
name: 无人机部署张宇豪算法
#json: ""
- id: deploy_kmeans_xieyaqi
name: 无人机部署算法
#json: ""
- id: deploy_empty
name: 测试算法
#json: ""
other-lists:
- id: map_wangzao
name: 通导态势图算法
#json: ""
- id: other_simulator
name: 模拟器服务
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
\ No newline at end of file
package com.hpcner.statusmanageservice;
import com.hpcner.statusmanageservice.bean.entity.EventInfo;
import com.hpcner.statusmanageservice.config.ServiceConfig;
import com.hpcner.statusmanageservice.serv.BaseService;
import com.hpcner.statusmanageservice.serv.ServiceFactory;
import com.hpcner.statusmanageservice.serv.deploy.DeployService;
import com.hpcner.statusmanageservice.serv.deploy.DeployXyqService;
import com.hpcner.statusmanageservice.service.database.EventInfoService;
import com.hpcner.statusmanageservice.utils.ApplicationContextUtil;
import com.hpcner.statusmanageservice.utils.TimeUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Map;
@SpringBootTest
@Slf4j
class StatusManageServiceApplicationTests {
@Resource
private EventInfoService eventInfoService;
@Test
void InsertEventInfo(){
EventInfo eventInfo = new EventInfo();
eventInfo.setEventName("TestEvent2");
eventInfo.setGmtCreate(TimeUtils.getNowTime());
eventInfo.setGmtModified(TimeUtils.getNowTime());
if(eventInfoService.InsertEventByName(eventInfo) == -1){
log.info("Event {} already exists",eventInfo.getEventName());
}else{
log.info("Event {} created",eventInfo.getEventName());
}
}
@Test
void Activate(){
EventInfo eventInfo = new EventInfo();
eventInfo.setEventName("TestEvent2");
if(eventInfoService.ActivateByName(eventInfo)) {
log.info("Event {} activated", eventInfo.getEventName());
}
else {
log.info("Event {} activate failed", eventInfo.getEventName());
}
}
@Test
void Deactivate(){
EventInfo eventInfo = new EventInfo();
eventInfo.setEventName("TestEvent2");
if(eventInfoService.DeactivateByName(eventInfo)) {
log.info("Event {} deactivated", eventInfo.getEventName());
}
else {
log.info("Event {} deactivate failed", eventInfo.getEventName());
}
}
@Test
void Delete(){
EventInfo eventInfo = new EventInfo();
eventInfo.setEventName("TestEvent2");
if(eventInfoService.DeleteEventByName(eventInfo)) {
log.info("Event {} deleted", eventInfo.getEventName());
}
else {
log.info("Event {} deleted failed", eventInfo.getEventName());
}
}
@Test
void Update(){
EventInfo eventInfo = new EventInfo();
eventInfo.setEventName("TestEvent2");
eventInfo.setEventLatitude(16.56);
eventInfo.setEventLongitude(123.0);
if(eventInfoService.UpdateEventByName(eventInfo)) {
log.info("Event {} updated", eventInfo.getEventName());
}
else {
log.info("Event {} updated failed", eventInfo.getEventName());
}
}
@Test
void Query(){
EventInfo eventInfo = eventInfoService.GetActivate();
if(eventInfo != null){
log.info("Event {} activated",eventInfo.getEventName());
}else{
log.info("No activated event");
}
eventInfoService.GetAllEventInfo().forEach(event -> {
log.info("Event {}",event.getEventName());
});
}
@Test
void GetService(){
Map<String, Map<String, BaseService>> serviceMap = ServiceFactory.serviceMap;
for(Map.Entry<String, Map<String, BaseService>> entry : serviceMap.entrySet()) {
String type = entry.getKey();
Map<String, BaseService> services = entry.getValue();
for (Map.Entry<String, BaseService> serviceEntry : services.entrySet()) {
BaseService service = serviceEntry.getValue();
log.info("Service type: {} id:{}", type,service.getId()); // 打印实际类型
//service.start("");
}
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment