This commit is contained in:
2026-01-17 08:59:21 +08:00
commit 1225e87dc9
31 changed files with 2260 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
package cc.amily49.api.module;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(scanBasePackages = "cc.amily49.api.module")
@EnableAsync
@EnableScheduling
@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO)
@EnableRedisRepositories(basePackages = {
// Add your redis repositories here
})
public class ModuleApplication {
public static void main(String[] args) {
SpringApplication.run(ModuleApplication.class, args);
}
}

View File

@@ -0,0 +1,82 @@
package cc.amily49.api.module.auth.filter;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import cc.amily49.api.module.auth.model.JwtUser;
import cc.amily49.api.module.auth.util.JwtUtil;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Stateless JWT Filter for Module Template
*
* @author Silence_Lurker by Gemini
*/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Resource
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
logger.warn("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
logger.warn("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// Validate token signature and expiration ONLY (Stateless)
if (jwtUtil.validateToken(jwtToken)) {
// Extract roles from token
List<String> roles = jwtUtil.getRolesFromToken(jwtToken);
Set<SimpleGrantedAuthority> authorities = null;
if (roles != null) {
authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
}
// Create stateless user details
JwtUser userDetails = new JwtUser(username, authorities);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
chain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,53 @@
package cc.amily49.api.module.auth.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
public class JwtUser implements UserDetails {
private final String username;
private final Set<? extends GrantedAuthority> authorities;
public JwtUser(String username, Set<? extends GrantedAuthority> authorities) {
this.username = username;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return null; // No password in token-based auth
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@@ -0,0 +1,85 @@
package cc.amily49.api.module.auth.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.io.Serializable;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.function.Function;
/**
* Utility class for handling JWT tokens.
* Generation, validation, etc.
*
* @author Silence_Lurker by Gemini
*/
@Component
public class JwtUtil implements Serializable {
private static final long serialVersionUID = -2550185165626007488L;
// Token validity in milliseconds (e.g., 10 hours)
public static final long JWT_TOKEN_VALIDITY = 10 * 60 * 60 * 1000;
@Value("${amily.jwt.secret}")
private String secretString;
private SecretKey secretKey;
@PostConstruct
public void init() {
byte[] decodedKey = Base64.getDecoder().decode(secretString);
this.secretKey = Keys.hmacShaKeyFor(decodedKey);
}
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public String getIpFromToken(String token) {
return getClaimFromToken(token, claims -> claims.get("ip", String.class));
}
public List<String> getRolesFromToken(String token) {
return getClaimFromToken(token, claims -> claims.get("roles", List.class));
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
/**
* Validate token (Stateless)
* Checks signature (implicit in getAllClaimsFromToken) and expiration.
*/
public Boolean validateToken(String token) {
try {
return !isTokenExpired(token);
} catch (Exception e) {
return false;
}
}
}

View File

@@ -0,0 +1,29 @@
package cc.amily49.api.module.common.controller;
import cc.amily49.api.module.common.service.SystemConfigService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import java.util.Map;
@RestController
@RequestMapping("/admin/config")
@PreAuthorize("hasRole('ADMIN')")
public class SystemConfigController {
@Resource
private SystemConfigService systemConfigService;
@GetMapping
public ResponseEntity<?> getAllConfigs() {
return ResponseEntity.ok(systemConfigService.getAllConfigs());
}
@PostMapping
public ResponseEntity<?> updateConfigs(@RequestBody Map<String, String> configs) {
systemConfigService.updateConfigs(configs);
return ResponseEntity.ok("Configuration updated successfully.");
}
}

View File

@@ -0,0 +1,19 @@
package cc.amily49.api.module.common.entity.po;
import jakarta.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name = "system_config")
public class SystemConfig {
@Id
@Column(name = "config_key", nullable = false)
private String key;
@Column(name = "config_value")
private String value;
@Column(name = "description")
private String description;
}

View File

@@ -0,0 +1,30 @@
package cc.amily49.api.module.common.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<?> handleIllegalArgumentException(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(Map.of("success", false, "message", e.getMessage()));
}
@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<?> handleIllegalStateException(IllegalStateException e) {
// Return 400 for business logic errors (like limit exceeded) or 409 Conflict if more appropriate
// Here 400 is fine for client errors.
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("success", false, "message", e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("success", false, "message", "æœ<EFBFBD>务器内部错è¯? " + e.getMessage()));
}
}

View File

@@ -0,0 +1,9 @@
package cc.amily49.api.module.common.repository.jpa;
import cc.amily49.api.module.common.entity.po.SystemConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SystemConfigRepository extends JpaRepository<SystemConfig, String> {
}

View File

@@ -0,0 +1,11 @@
package cc.amily49.api.module.common.service;
import java.util.Map;
public interface SystemConfigService {
String getConfig(String key, String defaultValue);
int getConfigInt(String key, int defaultValue);
void setConfig(String key, String value);
Map<String, String> getAllConfigs();
void updateConfigs(Map<String, String> configs);
}

View File

@@ -0,0 +1,57 @@
package cc.amily49.api.module.common.service.impl;
import cc.amily49.api.module.common.entity.po.SystemConfig;
import cc.amily49.api.module.common.repository.jpa.SystemConfigRepository;
import cc.amily49.api.module.common.service.SystemConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class SystemConfigServiceImpl implements SystemConfigService {
@Resource
private SystemConfigRepository systemConfigRepository;
@Override
public String getConfig(String key, String defaultValue) {
return systemConfigRepository.findById(key).map(SystemConfig::getValue).orElse(defaultValue);
}
@Override
public int getConfigInt(String key, int defaultValue) {
try {
return Integer.parseInt(getConfig(key, String.valueOf(defaultValue)));
} catch (NumberFormatException e) {
return defaultValue;
}
}
@Override
@Transactional
public void setConfig(String key, String value) {
SystemConfig config = systemConfigRepository.findById(key).orElse(new SystemConfig());
config.setKey(key);
config.setValue(value);
systemConfigRepository.save(config);
}
@Override
public Map<String, String> getAllConfigs() {
return systemConfigRepository.findAll().stream()
.collect(Collectors.toMap(SystemConfig::getKey, SystemConfig::getValue));
}
@Override
@Transactional
public void updateConfigs(Map<String, String> configs) {
for (Map.Entry<String, String> entry : configs.entrySet()) {
setConfig(entry.getKey(), entry.getValue());
}
}
}

View File

@@ -0,0 +1,31 @@
package cc.amily49.api.module.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(
new Components()
.addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")))
.info(new Info().title("Amily API").version("v1.0")
.description("API documentation for Amily project."));
}
}

View File

@@ -0,0 +1,17 @@
package cc.amily49.api.module.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class QuartzConfig {
@Bean
@QuartzDataSource
public DataSource quartzDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
return primaryDataSource;
}
}

View File

@@ -0,0 +1,71 @@
package cc.amily49.api.module.config;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import cc.amily49.api.module.auth.filter.JwtAuthenticationFilter;
import jakarta.annotation.Resource;
/**
* Security Configuration for Modules (Stateless, No Login)
*
* @author Silence_Lurker by Gemini
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Resource
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable())
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authz -> authz
// Swagger UI
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui.html").permitAll()
// Public endpoints (if any)
.requestMatchers("/public/**").permitAll()
// All other endpoints require authentication
.anyRequest().authenticated());
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration strictConfig = new CorsConfiguration();
strictConfig.setAllowedOriginPatterns(Arrays.asList(
"http://localhost:*",
"http://127.0.0.1:*",
"http://*.amily49.cc",
"https://*.amily49.cc",
"https://amily49.cc"
));
strictConfig.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
strictConfig.setAllowCredentials(true);
strictConfig.setAllowedHeaders(Arrays.asList("*"));
strictConfig.setExposedHeaders(Arrays.asList("Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", strictConfig);
return source;
}
}

View File

@@ -0,0 +1,39 @@
package cc.amily49.api.module.config.datasource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@Component
public class DataSourceWarmupRunner implements CommandLineRunner {
private final DataSource primaryDataSource;
public DataSourceWarmupRunner(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
this.primaryDataSource = primaryDataSource;
}
@Override
public void run(String... args) {
System.out.println("Wait for database connection warmup...");
long start = System.currentTimeMillis();
try (Connection conn = primaryDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT 1")) {
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
// Just consume result
}
}
long end = System.currentTimeMillis();
System.out.println("Database connection warmup completed in " + (end - start) + "ms.");
} catch (Exception e) {
System.err.println("Database warmup failed: " + e.getMessage());
// We don't throw exception here to allow app startup even if warmup fails,
// though it might fail later on actual requests.
}
}
}

View File

@@ -0,0 +1,63 @@
package cc.amily49.api.module.config.datasource;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = {
"cc.amily49.api.module.auth.repository.jpa",
"cc.amily49.api.module.common.repository.jpa"
},
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary"
)
public class PrimaryDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties("spring.datasource.primary.hikari")
public DataSource primaryDataSource() {
return primaryDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean(name = "entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
EntityManagerFactoryBuilder builder,
@Qualifier("primaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("cc.amily49.api.module.auth", "cc.amily49.api.module.common") // Explicitly scan business modules
.persistenceUnit("primary")
.build();
}
@Bean(name = "transactionManagerPrimary")
@Primary
public PlatformTransactionManager transactionManagerPrimary(
@Qualifier("entityManagerFactoryPrimary") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}

View File

@@ -0,0 +1,63 @@
package cc.amily49.api.module.config.datasource;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "cc.amily49.api.module.warehouse",
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary"
)
public class SecondaryDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSourceProperties secondaryDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties("spring.datasource.secondary.hikari")
public DataSource secondaryDataSource() {
return secondaryDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
EntityManagerFactoryBuilder builder,
@Qualifier("secondaryDataSource") DataSource dataSource) {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", "update"); // Auto-create tables for warehouse
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
return builder
.dataSource(dataSource)
.packages("cc.amily49.api.module.warehouse")
.persistenceUnit("secondary")
.properties(properties)
.build();
}
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManagerSecondary(
@Qualifier("entityManagerFactorySecondary") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}

View File

@@ -0,0 +1,146 @@
package cc.amily49.api.module.filter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import cc.amily49.api.module.warehouse.entity.OperationLog;
import cc.amily49.api.module.warehouse.service.LogService;
import jakarta.annotation.Resource;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Component
public class FullApiFilter implements Filter {
@Resource
private LogService logService;
@Value("${app.time-zone:Asia/Shanghai}")
private String appTimeZone;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// Wrap the request to cache the body content for logging
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(req);
long startTime = System.currentTimeMillis();
try {
// Use the wrapped request for the filter chain
chain.doFilter(wrappedRequest, response);
} catch (Exception e) {
req.setAttribute("filter_exception", e.getMessage());
throw e;
} finally {
try {
HttpServletResponse httpRes = (HttpServletResponse) response;
String servletPath = wrappedRequest.getServletPath();
String uri = wrappedRequest.getRequestURI();
// è·³è¿‡é«˜é¢æŽ¥å<C2A5>£æ—¥å¿—
if ("/message/newest".equals(servletPath)) {
return;
}
long duration = System.currentTimeMillis() - startTime;
String clientIp = getClientIp(wrappedRequest);
String method = wrappedRequest.getMethod();
String params;
// 登录接å<C2A5>£ç™»å½•æˆ<C3A6>功(状æ€<C3A6>ç <C3A7> 2xx)时ä¸<C3A4>记录å<E280A2>数,仅记录失败日å¿?
if ("/access/login".equals(servletPath) && httpRes.getStatus() >= 200 && httpRes.getStatus() < 300) {
params = "[PROTECTED]";
} else {
params = getParams(wrappedRequest);
}
OperationLog opLog = new OperationLog();
opLog.setIp(clientIp);
opLog.setUrl(uri);
opLog.setMethod(method);
opLog.setParams(params);
opLog.setDuration(duration);
opLog.setCreateTime(LocalDateTime.now(ZoneId.of(appTimeZone)));
opLog.setDescription("API Access Log");
// 获å<C2B7>当å‰<C3A5>登录用户
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
opLog.setUsername(auth.getName());
}
// 记录å<E280A2>¯èƒ½çš„å¼å¸¸ä¿¡æ<C2A1>?
Object exception = req.getAttribute("filter_exception");
if (exception != null) {
opLog.setException(exception.toString());
}
logService.saveLog(opLog);
} catch (Exception ex) {
System.err.println("Failed to save access log: " + ex.getMessage());
}
}
}
private String getParams(ContentCachingRequestWrapper request) {
StringBuilder params = new StringBuilder();
// Query String
String queryString = request.getQueryString();
if (queryString != null && !queryString.isEmpty()) {
params.append("Query: ").append(queryString);
}
// Body
// Note: ContentCachingRequestWrapper only caches content after it has been read.
// If the controller didn't read the body (e.g. GET request or error before reading), this will be empty.
byte[] content = request.getContentAsByteArray();
if (content.length > 0) {
if (params.length() > 0) {
params.append("; ");
}
try {
String body = new String(content, StandardCharsets.UTF_8);
// Simple truncation or formatting could be added here if needed
params.append("Body: ").append(body);
} catch (Exception e) {
params.append("Body: [Error reading body]");
}
}
return params.toString();
}
private String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && ip.contains(",")) {
ip = ip.split(",")[0].trim();
}
return ip;
}
}

View File

@@ -0,0 +1,98 @@
package cc.amily49.api.module.util;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
/**
* @author Silence_Lurker
*/
public class BaseEncoder {
public static enum Algorithm {
BASE64,
BASE64_URL,
HEX,
MD5,
SHA256,
SHA1,
REMOVE_SPECIAL_CHARS, // 你原æ<C5B8>¥çš„功能
URL_ENCODE
}
private BaseEncoder() {
}
public static String encodeByTarget(String target, Algorithm algorithm) {
if (target == null) {
return null;
}
try {
return switch (algorithm) {
case BASE64 -> encodeBase64(target);
case BASE64_URL -> encodeBase64Url(target);
case HEX -> encodeHex(target);
case MD5 -> encodeMD5(target);
case SHA256 -> encodeSHA256(target);
case SHA1 -> encodeSHA1(target);
case REMOVE_SPECIAL_CHARS -> removeSpecialChars(target);
case URL_ENCODE -> urlEncode(target);
};
} catch (Exception e) {
throw new RuntimeException("ç¼ç <EFBFBD>失败: " + e.getMessage(), e);
}
}
private static String encodeBase64(String target) {
return Base64.getEncoder().encodeToString(target.getBytes(StandardCharsets.UTF_8));
}
private static String encodeBase64Url(String target) {
return Base64.getUrlEncoder().encodeToString(target.getBytes(StandardCharsets.UTF_8));
}
private static String encodeHex(String target) {
byte[] bytes = target.getBytes(StandardCharsets.UTF_8);
return HexFormat.of().formatHex(bytes);
}
private static String encodeMD5(String target) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
}
private static String encodeSHA256(String target) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
}
private static String encodeSHA1(String target) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
}
private static String removeSpecialChars(String target) {
return target.replaceAll("[^a-zA-Z0-9]", "");
}
private static String urlEncode(String target) {
return java.net.URLEncoder.encode(target, StandardCharsets.UTF_8);
}
// é‡<C3A9>è½½æ¹æ³•,ä¿<C3A4>æŒ<C3A6>å<EFBFBD>å<E28098>Žå…¼å®?
public static String encodeByTarget(String target) {
return encodeByTarget(target, Algorithm.REMOVE_SPECIAL_CHARS);
}
// å·¥å…·æ¹æ³•:验è¯<C3A8>ç¼ç <C3A7>结æž?
public static boolean verify(String original, String encoded, Algorithm algorithm) {
String newEncoded = encodeByTarget(original, algorithm);
return newEncoded.equals(encoded);
}
}

View File

@@ -0,0 +1,17 @@
package cc.amily49.api.module.util;
/**
* @author Silence_Lurker
*/
public class UUIDGenerater {
private UUIDGenerater() {
}
public static String generate() {
return java.util.UUID.randomUUID().toString();
}
public static String generateWithSalt(byte[] salt) {
return java.util.UUID.nameUUIDFromBytes(salt).toString();
}
}

View File

@@ -0,0 +1,15 @@
package cc.amily49.api.module.warehouse.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
/**
* Operation description
*/
String value() default "";
}

View File

@@ -0,0 +1,137 @@
package cc.amily49.api.module.warehouse.aspect;
import cc.amily49.api.module.warehouse.annotation.Log;
import cc.amily49.api.module.warehouse.entity.OperationLog;
import cc.amily49.api.module.warehouse.service.LogService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.springframework.beans.factory.annotation.Value;
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class LogAspect {
private final LogService logService;
private final ObjectMapper objectMapper;
@Value("${app.time-zone:Asia/Shanghai}")
private String appTimeZone;
@Around("@annotation(logAnnotation)")
public Object around(ProceedingJoinPoint point, Log logAnnotation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = null;
String exceptionMsg = null;
try {
result = point.proceed();
} catch (Throwable e) {
exceptionMsg = e.getMessage();
throw e;
} finally {
long duration = System.currentTimeMillis() - startTime;
recordLog(point, logAnnotation, duration, exceptionMsg);
}
return result;
}
private void recordLog(ProceedingJoinPoint point, Log logAnnotation, long duration, String exceptionMsg) {
try {
MethodSignature signature = (MethodSignature) point.getSignature();
OperationLog operationLog = new OperationLog();
if (logAnnotation != null) {
operationLog.setDescription(logAnnotation.value());
}
// Method info
String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
operationLog.setClassMethod(className + "." + methodName + "()");
// Request info
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
operationLog.setUrl(request.getRequestURL().toString());
operationLog.setMethod(request.getMethod());
operationLog.setIp(getClientIp(request));
}
// Args (simplify params to avoid huge logs)
// 如果是登录成功,脱敏参数
if ("User Login".equals(logAnnotation.value()) && exceptionMsg == null) {
operationLog.setParams("[PROTECTED]");
} else {
try {
Object[] args = point.getArgs();
// Filter out non-serializable objects like HttpServletRequest,
// HttpServletResponse
Object[] filteredArgs = Arrays.stream(args)
.filter(arg -> !(arg instanceof jakarta.servlet.http.HttpServletRequest)
&& !(arg instanceof jakarta.servlet.http.HttpServletResponse)
&& !(arg instanceof org.springframework.web.multipart.MultipartFile))
.toArray();
String params = objectMapper.writeValueAsString(filteredArgs);
// Truncate if too long
if (params.length() > 2000) {
params = params.substring(0, 2000) + "...";
}
operationLog.setParams(params);
} catch (Exception e) {
operationLog.setParams("Failed to serialize args: " + e.getMessage());
}
}
// User info
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated() && !"anonymousUser".equals(authentication.getPrincipal())) {
operationLog.setUsername(authentication.getName());
} else {
operationLog.setUsername("Anonymous");
}
operationLog.setException(exceptionMsg);
operationLog.setDuration(duration);
operationLog.setCreateTime(LocalDateTime.now(ZoneId.of(appTimeZone)));
logService.saveLog(operationLog);
} catch (Exception e) {
log.error("LogAspect error", e);
}
}
private String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}

View File

@@ -0,0 +1,42 @@
package cc.amily49.api.module.warehouse.controller;
import cc.amily49.api.module.warehouse.entity.OperationLog;
import cc.amily49.api.module.warehouse.repository.OperationLogRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/logs")
@RequiredArgsConstructor
@Tag(name = "System Logs", description = "Operations for querying system logs")
public class LogController {
private final OperationLogRepository operationLogRepository;
@Operation(summary = "Get operation logs", description = "Retrieve paginated operation logs")
@PreAuthorize("hasRole('ADMIN')")
@GetMapping
public ResponseEntity<Page<OperationLog>> getLogs(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "createTime") String sortBy,
@RequestParam(defaultValue = "desc") String direction) {
Sort sort = Sort.by(Sort.Direction.fromString(direction), sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
Page<OperationLog> logs = operationLogRepository.findAll(pageable);
return ResponseEntity.ok(logs);
}
}

View File

@@ -0,0 +1,76 @@
package cc.amily49.api.module.warehouse.entity;
import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "operation_log")
public class OperationLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Operator username
*/
@Column(length = 50)
private String username;
/**
* Operation description (from annotation)
*/
@Column(length = 255)
private String description;
/**
* Request URL
*/
@Column(length = 500)
private String url;
/**
* HTTP Method (GET, POST, etc.)
*/
@Column(length = 10)
private String method;
/**
* Class and Method name called
*/
@Column(length = 255)
private String classMethod;
/**
* Client IP Address
*/
@Column(length = 50)
private String ip;
/**
* Request Parameters (JSON string, truncated if necessary)
*/
@Column(columnDefinition = "TEXT")
private String params;
/**
* Exception message if failed
*/
@Column(columnDefinition = "TEXT")
private String exception;
/**
* Execution duration in milliseconds
*/
private Long duration;
/**
* Operation time
*/
@Column(updatable = false)
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,9 @@
package cc.amily49.api.module.warehouse.repository;
import cc.amily49.api.module.warehouse.entity.OperationLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OperationLogRepository extends JpaRepository<OperationLog, Long> {
}

View File

@@ -0,0 +1,28 @@
package cc.amily49.api.module.warehouse.service;
import cc.amily49.api.module.warehouse.entity.OperationLog;
import cc.amily49.api.module.warehouse.repository.OperationLogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
public class LogService {
private final OperationLogRepository operationLogRepository;
/**
* Save log asynchronously
*/
@Async
public void saveLog(OperationLog logEntry) {
try {
operationLogRepository.save(logEntry);
} catch (Exception e) {
log.error("Failed to save operation log", e);
}
}
}

View File

@@ -0,0 +1,81 @@
spring.application.name=template-service
server.port=${SERVER_PORT:8080}
server.forward-headers-strategy=framework
# ===================================================================
# Primary DataSource (MySQL) - Business Data
# ===================================================================
spring.datasource.primary.hikari.connection-timeout=30000
spring.datasource.primary.hikari.maximum-pool-size=50
spring.datasource.primary.hikari.minimum-idle=10
spring.datasource.primary.hikari.idle-timeout=300000
spring.datasource.primary.hikari.max-lifetime=600000
spring.datasource.primary.hikari.keepalive-time=60000
spring.datasource.primary.hikari.connection-test-query=SELECT 1
spring.datasource.primary.hikari.validation-timeout=5000
spring.datasource.primary.hikari.leak-detection-threshold=60000
# 数据库配置
spring.datasource.primary.url=${DB_URL:jdbc:mysql://127.0.0.1:3306/template_db?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai}
spring.datasource.primary.username=${DB_USERNAME:root}
spring.datasource.primary.password=${DB_PASSWORD:}
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
# Flyway
spring.jpa.hibernate.ddl-auto=validate
# ===================================================================
# Secondary DataSource (PostgreSQL) - Warehouse / Logs
# ===================================================================
spring.datasource.secondary.url=${WAREHOUSE_DB_URL:jdbc:postgresql://127.0.0.1:5432/template_warehouse}
spring.datasource.secondary.username=${WAREHOUSE_DB_USERNAME:postgres}
spring.datasource.secondary.password=${WAREHOUSE_DB_PASSWORD:postgres}
spring.datasource.secondary.driver-class-name=org.postgresql.Driver
spring.datasource.secondary.hikari.connection-timeout=30000
spring.datasource.secondary.hikari.maximum-pool-size=20
spring.datasource.secondary.hikari.minimum-idle=5
spring.datasource.secondary.hikari.keepalive-time=60000
# OpenAPI / Swagger
springdoc.swagger-ui.enabled=true
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.operationsSorter=alpha
springdoc.swagger-ui.tagsSorter=alpha
springdoc.swagger-ui.display-request-duration=true
# Redis
spring.data.redis.host=${REDIS_HOST:localhost}
spring.data.redis.port=6379
spring.data.redis.password=${REDIS_PWD:}
# JWT Secret Key Configuration
# IMPORTANT: Replace this in production!
amily.jwt.secret=${AMILY_JWT_SECRET:YyNTIzL1snXG0oISVeKFNeJWUhXSpVLSpALXtNWyNeOXIgWyZePShNVHlYPl0uPnZDJV45UnIuWyZeIChNUHlYPl0uPnZD}
# Mail Configuration
spring.mail.host=${MAIL_HOST:smtp.example.com}
spring.mail.port=${MAIL_PORT:587}
spring.mail.username=${MAIL_USERNAME:}
spring.mail.password=${MAIL_PASSWORD:}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.debug=false
spring.mail.default-encoding=UTF-8
# Timezone
app.time-zone=${APP_TIMEZONE:Asia/Shanghai}
spring.jackson.time-zone=${app.time-zone}
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# Quartz Scheduler
spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=never
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_
spring.quartz.properties.org.quartz.jobStore.isClustered=false
spring.quartz.properties.org.quartz.scheduler.instanceName=TemplateScheduler
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO

View File

@@ -0,0 +1,258 @@
-- V1__Init_Template_Schema.sql
-- ====================================================================================
-- Auth Module
-- ====================================================================================
-- Create user_account_login_info table
CREATE TABLE IF NOT EXISTS user_account_login_info (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE,
nickname VARCHAR(255),
email VARCHAR(255) UNIQUE,
access_code VARCHAR(255),
salt VARCHAR(255),
allow_ip_change BIT(1) NOT NULL,
last_login_ip VARCHAR(255)
);
-- Create role table
CREATE TABLE IF NOT EXISTS role (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE
);
-- Create user_roles join table
CREATE TABLE IF NOT EXISTS user_roles (
user_id BIGINT NOT NULL,
role_id INT NOT NULL,
PRIMARY KEY (user_id, role_id),
FOREIGN KEY (user_id) REFERENCES user_account_login_info(id),
FOREIGN KEY (role_id) REFERENCES role(id)
);
-- Create user_access_info table
CREATE TABLE IF NOT EXISTS user_access_info (
uuid VARCHAR(36) PRIMARY KEY,
user_id BIGINT UNIQUE,
FOREIGN KEY (user_id) REFERENCES user_account_login_info(id)
);
-- Create api_access_info table
CREATE TABLE IF NOT EXISTS api_access_info (
id VARCHAR(36) PRIMARY KEY,
access_code VARCHAR(255),
access_name VARCHAR(255),
access_uri VARCHAR(255),
access_uri_regex VARCHAR(255),
access_token VARCHAR(255),
user_access_info_id VARCHAR(36),
FOREIGN KEY (user_access_info_id) REFERENCES user_access_info(uuid)
);
-- Insert default roles
INSERT INTO role (name) SELECT 'ADMIN' WHERE NOT EXISTS (SELECT 1 FROM role WHERE name = 'ADMIN');
INSERT INTO role (name) SELECT 'USER' WHERE NOT EXISTS (SELECT 1 FROM role WHERE name = 'USER');
-- ====================================================================================
-- Common / Config Module
-- ====================================================================================
-- Create system_config table for dynamic settings
CREATE TABLE IF NOT EXISTS system_config (
config_key VARCHAR(100) NOT NULL PRIMARY KEY,
config_value VARCHAR(500),
description VARCHAR(255)
);
-- ====================================================================================
-- Warehouse / Log Module
-- ====================================================================================
CREATE TABLE IF NOT EXISTS operation_log (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
description VARCHAR(255),
url VARCHAR(500),
method VARCHAR(10),
class_method VARCHAR(255),
ip VARCHAR(50),
params TEXT,
exception TEXT,
duration BIGINT,
create_time DATETIME
);
-- ====================================================================================
-- Quartz Scheduler Module
-- ====================================================================================
DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
DROP TABLE IF EXISTS QRTZ_LOCKS;
DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
DROP TABLE IF EXISTS QRTZ_CALENDARS;
CREATE TABLE QRTZ_JOB_DETAILS(
SCHED_NAME VARCHAR(120) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
JOB_CLASS_NAME VARCHAR(250) NOT NULL,
IS_DURABLE VARCHAR(1) NOT NULL,
IS_NONCONCURRENT VARCHAR(1) NOT NULL,
IS_UPDATE_DATA VARCHAR(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
JOB_NAME VARCHAR(200) NOT NULL,
JOB_GROUP VARCHAR(200) NOT NULL,
DESCRIPTION VARCHAR(250) NULL,
NEXT_FIRE_TIME BIGINT(13) NULL,
PREV_FIRE_TIME BIGINT(13) NULL,
PRIORITY INTEGER NULL,
TRIGGER_STATE VARCHAR(16) NOT NULL,
TRIGGER_TYPE VARCHAR(8) NOT NULL,
START_TIME BIGINT(13) NOT NULL,
END_TIME BIGINT(13) NULL,
CALENDAR_NAME VARCHAR(200) NULL,
MISFIRE_INSTR SMALLINT(2) NULL,
JOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_SIMPLE_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
REPEAT_COUNT BIGINT(7) NOT NULL,
REPEAT_INTERVAL BIGINT(12) NOT NULL,
TIMES_TRIGGERED BIGINT(10) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_CRON_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
CRON_EXPRESSION VARCHAR(120) NOT NULL,
TIME_ZONE_ID VARCHAR(80),
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_SIMPROP_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
STR_PROP_1 VARCHAR(512) NULL,
STR_PROP_2 VARCHAR(512) NULL,
STR_PROP_3 VARCHAR(512) NULL,
INT_PROP_1 INT NULL,
INT_PROP_2 INT NULL,
LONG_PROP_1 BIGINT NULL,
LONG_PROP_2 BIGINT NULL,
DEC_PROP_1 NUMERIC(13,4) NULL,
DEC_PROP_2 NUMERIC(13,4) NULL,
BOOL_PROP_1 VARCHAR(1) NULL,
BOOL_PROP_2 VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_BLOB_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
BLOB_DATA BLOB NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP),
FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_CALENDARS (
SCHED_NAME VARCHAR(120) NOT NULL,
CALENDAR_NAME VARCHAR(200) NOT NULL,
CALENDAR BLOB NOT NULL,
PRIMARY KEY (SCHED_NAME,CALENDAR_NAME))
ENGINE=InnoDB;
CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS (
SCHED_NAME VARCHAR(120) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP))
ENGINE=InnoDB;
CREATE TABLE QRTZ_FIRED_TRIGGERS (
SCHED_NAME VARCHAR(120) NOT NULL,
ENTRY_ID VARCHAR(95) NOT NULL,
TRIGGER_NAME VARCHAR(200) NOT NULL,
TRIGGER_GROUP VARCHAR(200) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
FIRED_TIME BIGINT(13) NOT NULL,
SCHED_TIME BIGINT(13) NOT NULL,
PRIORITY INTEGER NOT NULL,
STATE VARCHAR(16) NOT NULL,
JOB_NAME VARCHAR(200) NULL,
JOB_GROUP VARCHAR(200) NULL,
IS_NONCONCURRENT VARCHAR(1) NULL,
REQUESTS_RECOVERY VARCHAR(1) NULL,
PRIMARY KEY (SCHED_NAME,ENTRY_ID))
ENGINE=InnoDB;
CREATE TABLE QRTZ_SCHEDULER_STATE (
SCHED_NAME VARCHAR(120) NOT NULL,
INSTANCE_NAME VARCHAR(200) NOT NULL,
LAST_CHECKIN_TIME BIGINT(13) NOT NULL,
CHECKIN_INTERVAL BIGINT(13) NOT NULL,
PRIMARY KEY (SCHED_NAME,INSTANCE_NAME))
ENGINE=InnoDB;
CREATE TABLE QRTZ_LOCKS (
SCHED_NAME VARCHAR(120) NOT NULL,
LOCK_NAME VARCHAR(40) NOT NULL,
PRIMARY KEY (SCHED_NAME,LOCK_NAME))
ENGINE=InnoDB;
CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME);
CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME);
CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP);
CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP);
commit;