提交 97221fc7 authored 作者: 黄承天's avatar 黄承天

Initial commit

上级
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
差异被折叠。
@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 https://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 Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?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>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tykj</groupId>
<artifactId>datahouse</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>datahouse</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<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.tykj.datahouse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 启动类
* @author admin
*/
@Slf4j
@SpringBootApplication
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
log.info( "请开发者喝杯咖啡:\n"+
"█▀▀▀▀▀▀▀█▀▀▀█▀▀▀█▀▀▀█▀█▀▀▀▀▀▀▀█\n" +
"█ █▀▀▀█ █ ▄ ▀█▄▀█▀▀▀▄▀█ █▀▀▀█ █\n" +
"█ █ █ █▄▄█▄█▀ ▄ ▄ ▀▄█ █ █ █\n" +
"█ ▀▀▀▀▀ █ █▀▄ █▀█▀█▀▄ █ ▀▀▀▀▀ █\n" +
"█▀▀██▀▀▀██▄█▀▄▀█▀▄▄██▀██▀█▀▀▀▀█\n" +
"█▀▄▄▄ ▄▀ ▄▄▀ ▄ ██ ▀▄ ▄▀ █\n" +
"█ ▀ ██▀▀██ ▄▀▀███ ▄▄ ▄█ ▀█▄▄█\n" +
"█▀▄█▀ █▀▀ ███ █ ▄███▀▄ ▄▄▀▀▄ █\n" +
"█▀█▀▄▄ ▀▀▄ ▀▀▄▀▄ ▄ █▀▀ █▄▀▀█▄ █\n" +
"█▄▄▀▀ ▀▀ █▀▀▀ ▄█ ▀██▀▀ ▄▀▀▄ █\n" +
"█▀▀▀▀█▀▀██▄▀▄▀▀██▀ █ ▀ ▀ █▀██\n" +
"█▀▀▀▀▀▀▀█▄█▀██▄▀ ▀ █▀ █▀█ █ ▄ █\n" +
"█ █▀▀▀█ █ █▀▀▄▀▀▀█ █▀ ▀▀▀ ██▄▀█\n" +
"█ █ █ ███▀▀ ▀ ▀ ▄▄█▄▄▀ █▄ ▀ █\n" +
"█ ▀▀▀▀▀ █ █▄▀ ██▀ ██▀█▄ █ ▄█\n" +
"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀");
}
}
package com.tykj.datahouse.base.config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author huangjiafu
* @version V1.0
* @data 2021/7/15 10:46
**/
@Component
public class BeanFactory {
@Bean
ClassLoader initClassLoader(){
return getClass().getClassLoader();
}
}
package com.tykj.datahouse.base.config;
import com.google.common.collect.Sets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Arrays;
import java.util.Collections;
/**
* @author LJJ cnljj1995@gmail.com
* on 2020-04-26
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.produces(Sets.newHashSet("application/json"))
.consumes(Sets.newHashSet("application/json"))
.protocols(Sets.newHashSet("https", "http"))
.apiInfo(apiInfo())
.forCodeGeneration(true)
.useDefaultResponseMessages(true)
// .globalResponseMessage(RequestMethod.GET, getResMsg())
.select()
// 指定controller存放的目录路径
// .apis(RequestHandlerSelectors.withClassAnnotation(AutoDocument.class))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(Collections.singletonList(securityContext()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 文档标题
.title("工作流接口文档")
// 文档描述
.description("工作流")
.termsOfServiceUrl("git地址待更新")
.version("v1")
.contact(new Contact("efs", "git", "ty@example.com"))
.build();
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("spring_oauth", scopes())))
.forPaths(PathSelectors.any())
.build();
}
private SecurityScheme securityScheme() {
GrantType grantType = new ResourceOwnerPasswordCredentialsGrant("/user/login");
return new OAuthBuilder()
.name("spring_oauth")
.grantTypes(Collections.singletonList(grantType))
.scopes(Arrays.asList(scopes()))
.build();
}
private AuthorizationScope[] scopes() {
return new AuthorizationScope[]{
new AuthorizationScope("all", "All scope is trusted!")
};
}
}
package com.tykj.datahouse.base.config;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.stereotype.Component;
/**
* @author huangjiafu
* @version V1.0
* @data 2021/7/15 9:49
**/
@Component
public class ToUpperCase extends PhysicalNamingStrategyStandardImpl {
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
return Identifier.toIdentifier(name.getText().toUpperCase());
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
return Identifier.toIdentifier(name.getText().toUpperCase());
}
}
package com.tykj.datahouse.base.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
/**
* @author zsp
* @version V1.0
* @class WebMvcConfig
* @packageName com.example.personnelmanager.common.config
* @data 2020/6/11
**/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
.maxAge(3600);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/workflow/xml/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + File.separator+"xml"+File.separator);
// .addResourceLocations("file:" + System.getProperty("user.dir") +"\\xml\\");
registry.addResourceHandler("/xml/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + File.separator+"xml"+File.separator);
// .addResourceLocations("file:" + System.getProperty("user.dir") + "\\xml\\");
registry.addResourceHandler("/workflow/**")
.addResourceLocations("classpath:/workflow/");
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
};
}
}
package com.tykj.datahouse.base.exception;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.tykj.datahouse.base.result.ApiException;
import com.tykj.datahouse.base.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import java.sql.SQLSyntaxErrorException;
/**
* 错误处理类
* 所有的报错信息都会通过本层的方法向外界返回
*
* @author HuangXiahao
**/
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理字段长度异常
* @param invalidFormatException
* @return
*/
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity handle(InvalidFormatException invalidFormatException){
log.warn(invalidFormatException.toString());
return ResultUtil.failed("字段长度错误,请修改为合适的长度!");
}
@ExceptionHandler(SQLSyntaxErrorException.class)
public ResponseEntity handleSQl(InvalidFormatException invalidFormatException){
log.warn(invalidFormatException.toString());
return ResultUtil.failed("列名不合法,请修改列名!");
}
/**
* 业务错误
*
* @param e 报错信息
*/
@ResponseBody
@ExceptionHandler(ApiException.class)
public ResponseEntity errorMessage(ApiException e) {
log.warn("[自定义异常] {}", e.toString());
if (e.getResponseEntity() != null) {
return e.getResponseEntity();
}
return ResultUtil.failed(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity errorMessage(Exception e) {
e.printStackTrace();
return ResultUtil.failed(e.getMessage());
}
}
package com.tykj.datahouse.base.result;
import org.springframework.http.ResponseEntity;
/**
* 全局错误处理类,用于处理一些不容易定义的错误
*
* @author HuangXiahao
**/
public class ApiException extends RuntimeException {
private ResponseEntity responseEntity;
public ApiException(ResponseEntity responseEntity) {
this.responseEntity = responseEntity;
}
public ApiException(String message) {
this.responseEntity = ResponseEntity.status(500).body(new ResultObj("",message));
}
public ApiException( Object data,String message) {
this.responseEntity = ResponseEntity.status(500).body(new ResultObj(data, message));
}
public ResponseEntity getResponseEntity() {
return responseEntity;
}
public void setResponseEntity(ResponseEntity responseEntity) {
this.responseEntity = responseEntity;
}
}
package com.tykj.datahouse.base.result;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author dengdiyi
* @description 接口返回统一标准类
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonPropertyOrder(value = {"message", "data"})
public class ResultObj<T> {
private T data;
private String message;
public ResultObj(T o) {
this.data = o;
this.message = "no message";
}
}
package com.tykj.datahouse.base.result;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* @author HuangXiahao
* @version V1.0
* @class ResultMessage
* @packageName com.example.hello.demo.resultObject
**/
public class ResultUtil<T> {
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> ResponseEntity<ResultObj<T>> success(T data,String message) {
return ResponseEntity.ok(new ResultObj<>(data,message));
}
/**
* 成功返回结果
*/
public static <T> ResponseEntity<ResultObj<T>> success(String message) {
return ResponseEntity.ok(new ResultObj<>(null,message));
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> ResponseEntity success(T data, HttpHeaders headers) {
return new ResponseEntity(new ResultObj(data), headers, HttpStatus.OK);
}
/**
* 失败返回结果
*/
public static <T> ResponseEntity failed() {
return ResponseEntity.status(500).body(new ResultObj("服务器内部发生错误"));
}
/**
* 失败返回结果
*/
public static <T> ResponseEntity failed(T content) {
return new ResponseEntity(new ResultObj(content), HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* 失败返回结果
*/
public static <T> ResponseEntity failed(HttpStatus httpStatus) {
return new ResponseEntity(httpStatus);
}
/**
* 失败返回结果
*/
public static <T> ResponseEntity failed(HttpStatus httpStatus, T content) {
return new ResponseEntity(new ResultObj(content), httpStatus);
}
/**
* 参数验证失败返回结果
*/
public static <T> ResponseEntity validateFailed(T content) {
return failed(HttpStatus.INTERNAL_SERVER_ERROR, content);
}
/**
* 未登录返回结果
*/
public static <T> ResponseEntity unauthorized() {
return failed(HttpStatus.UNAUTHORIZED);
}
/**
* 未授权返回结果
*/
public static <T> ResponseEntity forbidden() {
return failed(HttpStatus.FORBIDDEN);
}
}
package com.tykj.datahouse.base.util;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class ClassUtil {
/**
* 读取项目中所有Class 并以Class对象的集合返回
* @param load ClassLoader
* @return Class对象集合
*/
public static List<Class<?>> loadClassByLoader(ClassLoader load) {
List<Class<?>> classes = new ArrayList<>();
try {
Enumeration<URL> urls = load.getResources("");
//放所有类型
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
//文件类型(其实是文件夹)
if (url.getProtocol().equals("file")) {
loadClassByPath(null, url.getPath(), classes, load);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 通过文件路径加载所有类 root 主要用来替换path中前缀(除包路径以外的路径)
*/
private static void loadClassByPath(String root, String path, List<Class<?>> list, ClassLoader load) {
File f = new File(path);
if (root == null) {
root = f.getPath();
}
//判断是否是class文件
if (f.isFile() && f.getName().matches("^.*\\.class$")) {
try {
String classPath = f.getPath();
//截取出className 将路径分割符替换为.(windows是\ linux、mac是/)
String className = classPath.substring(root.length() + 1, classPath.length() - 6).replace('/', '.').replace('\\', '.');
list.add(load.loadClass(className));
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
File[] fs = f.listFiles();
if (fs == null) {
return;
}
for (File file : fs) {
loadClassByPath(root, file.getPath(), list, load);
}
}
}
}
package com.tykj.datahouse.base.util;
import java.io.*;
/**
* @author HuangXiahao
* @version V1.0
* @class FileUtil
* @packageName com.tykj.workflowcore.base.util
**/
public class FileUtil {
public static File createFileByString(String filePath,String fileString){
File f = null;
try {
f = new File(filePath);
// 判断文件是否存在
if(!f.exists()){
f.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new StringReader(fileString));
bufferedWriter = new BufferedWriter(new FileWriter(f));
//字符缓冲区
char buf[] = new char[1024];
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return f;
}
}
package com.tykj.datahouse.controller;
import com.tykj.datahouse.service.TableInfoService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(tags = "基础模型接口")
@CrossOrigin
@RequestMapping("/tableinfo")
@RestController
public class TableInfoController {
@Autowired
private TableInfoService tableInfoService;
}
package com.tykj.datahouse.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.util.List;
@Accessors(chain = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class ColumnInfo {
@Id
@ApiModelProperty("主键")
@JsonIgnore
private Integer id;
//-----------------------------//
@ApiModelProperty(value = "是否是主键 true/false", position = 1)
private Boolean isPrimary;
@ApiModelProperty(value = "列名", position = 2)
private String name;
@ApiModelProperty(value = "别名", position = 3)
private String alias;
@ApiModelProperty(value = "列类型", position = 4)
private String type;
@ApiModelProperty(value = "长度", position = 5)
private Integer length;
@ApiModelProperty(value = "描述", position = 6)
private String description;
@JsonIgnore
private Integer tableInfoId;
}
package com.tykj.datahouse.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class Quote {
@Id
@ApiModelProperty("主键")
@JsonIgnore
private Integer id;
@ApiModelProperty(value = "值")
private String value;
@JsonIgnore
private Integer columnInfoId;
}
package com.tykj.datahouse.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class TableInfo {
@Id
@ApiModelProperty("主键")
private Integer id;
@ApiModelProperty(value = "创建时间", position = 1)
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd hh:mm")
private Date createdTime;
@ApiModelProperty(value = "修改时间", position = 2)
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd hh:mm")
private Date updatedTime;
//------------------------------//
@ApiModelProperty(value = "表名", position = 3)
private String name;
@ApiModelProperty(value = "别名", position = 4)
private String alias;
@ApiModelProperty(value = "描述", position = 5)
private String description;
@Transient
@ApiModelProperty(value = "字段信息", position = 8)
private List<ColumnInfo> columnInfos;
}
package com.tykj.datahouse.repository;
import com.tykj.datahouse.entity.ColumnInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
import java.util.List;
public interface ColumnInfoRepository extends JpaRepository<ColumnInfo, Integer> {
List<ColumnInfo> findByTableInfoId(Integer tableInfoId);
@Transactional
void deleteAllByTableInfoId(Integer tableInfoId);
}
package com.tykj.datahouse.repository;
import com.tykj.datahouse.entity.Quote;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
import java.util.List;
public interface QuoteRepository extends JpaRepository<Quote, Integer> {
List<Quote> findByColumnInfoId(Integer columnInfoId);
@Transactional
void deleteAllByColumnInfoId(Integer columnInfoId);
}
package com.tykj.datahouse.repository;
import com.tykj.datahouse.entity.TableInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TableInfoRepository extends JpaRepository<TableInfo, Integer> {
boolean existsByName(String name);
Integer countByName(String name);
List<TableInfo> findByName(String name);
void deleteAllByName(String name);
}
package com.tykj.datahouse.service;
import org.springframework.stereotype.Service;
@Service
public class TableInfoService {
}
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
datasource:
username: root
password: root
url: jdbc:mysql://192.168.100.248:3306/datahouse?useSSL=true&verifyServerCertificate=false&useUnicode=true&autoReconnect=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
read-only: false
connection-timeout: 60000
idle-timeout: 60000
validation-timeout: 3000
max-lifetime: 60000
login-timeout: 5
maximum-pool-size: 60
minimum-idle: 10
jpa:
show-sql: true
hibernate:
naming:
physical-strategy: com.tykj.datahouse.base.config.ToUpperCase
ddl-auto: update
database-platform: org.hibernate.dialect.MySQL8Dialect
server:
port: 13765
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
datasource:
username: PUNISH
password: 123456
url: jdbc:oscar://192.168.102.200:2003/OSRDB
driver-class-name: com.oscar.Driver
hikari:
read-only: false
connection-timeout: 60000
idle-timeout: 60000
validation-timeout: 3000
max-lifetime: 60000
login-timeout: 5
maximum-pool-size: 60
minimum-idle: 10
jpa:
show-sql: true
hibernate:
ddl-auto: update
database-platform: org.hibernate.dialect.OscarDialect
server:
port: 8800
\ No newline at end of file
spring:
profiles:
active: mysql
\ No newline at end of file
package com.tykj.datahouse;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DatahouseApplicationTests {
@Test
void contextLoads() {
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论