Commit caa9451d by 袁伟铭

Merge remote-tracking branch 'origin/master'

parents 736e13e2 cfe4c3e5
......@@ -29,6 +29,11 @@
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.zq</groupId>
<artifactId>logging-server</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
......@@ -154,13 +159,6 @@
<version>0.1.55</version>
</dependency>
<!-- 解析客户端操作系统、浏览器信息 -->
<dependency>
<groupId>nl.basjes.parse.useragent</groupId>
<artifactId>yauaa</artifactId>
<version>5.23</version>
</dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
......@@ -192,6 +190,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 打包时跳过测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<!-- 使用@profiles.active@需要添加以下内容 -->
......
package com.zq.admin;
import com.zq.common.annotation.rest.AnonymousGetMapping;
import com.zq.common.config.base.SpringContextHolder;
import io.swagger.annotations.Api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
......@@ -24,7 +24,8 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableTransactionManagement
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@SpringBootApplication(scanBasePackages = {"com.zq.admin", "com.zq.common.config"})
@MapperScan({"com.zq.*.mapper", "com.zq.*.dao"})
@SpringBootApplication(scanBasePackages = {"com.zq.admin", "com.zq.logging", "com.zq.common.config"})
public class AdminApplication {
public static void main(String[] args) {
......@@ -32,11 +33,6 @@ public class AdminApplication {
}
@Bean
public SpringContextHolder springContextHolder() {
return new SpringContextHolder();
}
@Bean
public ServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
fa.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
......@@ -53,4 +49,4 @@ public class AdminApplication {
return "Backend service started successfully";
}
}
\ No newline at end of file
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.annotation;
package com.zq.admin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
......@@ -45,4 +45,5 @@ public @interface DataPermission {
* Entity 中与部门关联的字段名称
*/
String joinName() default "";
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.annotation;
package com.zq.admin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
......@@ -30,6 +30,7 @@ public @interface Query {
// Dong ZhaoYang 2017/8/7 基本对象的属性名
String propName() default "";
// Dong ZhaoYang 2017/8/7 查询方式
Type type() default Type.EQUAL;
......@@ -82,7 +83,9 @@ public @interface Query {
* 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询
*/
enum Join {
/** jie 2019-6-4 13:18:30 */
/**
* jie 2019-6-4 13:18:30
*/
LEFT, RIGHT, INNER
}
......
package com.zq.system.base;
package com.zq.admin.base;
import lombok.Getter;
import lombok.Setter;
......@@ -14,7 +14,7 @@ import java.sql.Timestamp;
*/
@Getter
@Setter
public class BaseDTO implements Serializable {
public class BaseDTO implements Serializable {
private String createBy;
......@@ -38,4 +38,5 @@ public class BaseDTO implements Serializable {
}
return builder.toString();
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.base;
package com.zq.admin.base;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
......@@ -34,6 +34,7 @@ import java.sql.Timestamp;
/**
* 通用字段, is_del 根据需求自行添加
*
* @author Zheng Jie
* @Date 2019年10月24日20:46:32
*/
......@@ -64,10 +65,14 @@ public class BaseEntity implements Serializable {
private Timestamp updateTime;
/* 分组校验 */
public @interface Create {}
public @interface Create {
}
/* 分组校验 */
public @interface Update {}
public @interface Update {
}
@Override
public String toString() {
......@@ -83,4 +88,5 @@ public class BaseEntity implements Serializable {
}
return builder.toString();
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.base;
package com.zq.admin.base;
import java.util.List;
......@@ -25,6 +25,7 @@ public interface BaseMapper<D, E> {
/**
* DTO转Entity
*
* @param dto /
* @return /
*/
......@@ -32,6 +33,7 @@ public interface BaseMapper<D, E> {
/**
* Entity转DTO
*
* @param entity /
* @return /
*/
......@@ -39,6 +41,7 @@ public interface BaseMapper<D, E> {
/**
* DTO集合转Entity集合
*
* @param dtoList /
* @return /
*/
......@@ -46,8 +49,10 @@ public interface BaseMapper<D, E> {
/**
* Entity集合转DTO集合
*
* @param entityList /
* @return /
*/
List<D> toDto(List<E> entityList);
}
......@@ -13,17 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import com.zq.system.utils.SecurityUtils;
import com.zq.admin.utils.SecurityUtils;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import java.util.Optional;
/**
* @description : 设置审计
* @author : Dong ZhaoYang
* @author : Dong ZhaoYang
* @description : 设置审计
* @date : 2019/10/28
*/
@Component("auditorAware")
......@@ -39,8 +39,10 @@ public class AuditorConfig implements AuditorAware<String> {
try {
// 这里应根据实际业务情况获取具体信息
return Optional.of(SecurityUtils.getCurrentUsername());
}catch (Exception ignored){}
} catch (Exception ignored) {
}
// 用户定时任务,或者无Token调用的情况
return Optional.of("System");
}
}
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import com.zq.system.config.bean.LoginProperties;
import com.zq.admin.config.bean.LoginProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import com.zq.system.utils.SecurityUtils;
import com.zq.admin.utils.SecurityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
......@@ -35,4 +35,5 @@ public class ElPermissionConfig {
// 判断当前用户的所有权限是否包含接口上定义的权限
return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains);
}
}
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import com.zq.common.constant.CloudConstant;
import com.zq.admin.constant.AdminConstant;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
......@@ -46,9 +46,9 @@ public class FileProperties {
public ElPath getPath() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith(CloudConstant.WIN)) {
if (os.toLowerCase().startsWith(AdminConstant.WIN)) {
return windows;
} else if (os.toLowerCase().startsWith(CloudConstant.MAC)) {
} else if (os.toLowerCase().startsWith(AdminConstant.MAC)) {
return mac;
}
return linux;
......@@ -60,5 +60,7 @@ public class FileProperties {
private String path;
private String avatar;
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
......@@ -35,4 +35,5 @@ public class RsaProperties {
public void setPrivateKey(String privateKey) {
RsaProperties.privateKey = privateKey;
}
}
\ No newline at end of file
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.config;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Predicates;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.domain.Pageable;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRuleConvention;
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.ArrayList;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
/**
* api页面 /doc.html
*
* @author Zheng Jie
* @date 2018-11-23
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${jwt.header}")
private String tokenHeader;
@Value("${swagger.enabled}")
private Boolean enabled;
@Bean
@SuppressWarnings("all")
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(enabled)
.pathMapping("/")
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.paths(PathSelectors.any())
.build()
//添加登陆认证
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.description("一个简单且易上手的 Spring boot 后台管理框架")
.title("EL-ADMIN 接口文档")
.version("2.6")
.build();
}
private List<SecurityScheme> securitySchemes() {
//设置请求头信息
List<SecurityScheme> securitySchemes = new ArrayList<>();
ApiKey apiKey = new ApiKey(tokenHeader, tokenHeader, "header");
securitySchemes.add(apiKey);
return securitySchemes;
}
private List<SecurityContext> securityContexts() {
//设置需要登录认证的路径
List<SecurityContext> securityContexts = new ArrayList<>();
// ^(?!auth).*$ 表示所有包含auth的接口不需要使用securitySchemes即不需要带token
// ^标识开始 ()里是一子表达式 ?!/auth表示匹配不是/auth的位置,匹配上则添加请求头,注意路径已/开头 .表示任意字符 *表示前面的字符匹配多次 $标识结束
securityContexts.add(getContextByPath());
return securityContexts;
}
private SecurityContext getContextByPath() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!/auth).*$"))
.build();
}
private List<SecurityReference> defaultAuth() {
List<SecurityReference> securityReferences = new ArrayList<>();
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes));
return securityReferences;
}
}
/**
* 将Pageable转换展示在swagger中
*/
@Configuration
class SwaggerDataConfig {
@Bean
public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) {
return new AlternateTypeRuleConvention() {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
public List<AlternateTypeRule> rules() {
return newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class)));
}
};
}
@ApiModel
@Data
private static class Page {
@ApiModelProperty("页码 (0..N)")
private Integer page;
@ApiModelProperty("每页显示的数目")
private Integer size;
@ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc")
private List<String> sort;
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config;
package com.zq.admin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -26,8 +26,9 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.bean;
package com.zq.admin.config.bean;
import lombok.Data;
......@@ -58,4 +58,5 @@ public class LoginCode {
public LoginCodeEnum getCodeType() {
return codeType;
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.bean;
package com.zq.admin.config.bean;
/**
* 验证码配置枚举
......@@ -26,18 +26,18 @@ public enum LoginCodeEnum {
/**
* 算数
*/
arithmetic,
ARITHMETIC,
/**
* 中文
*/
chinese,
CHINESE,
/**
* 中文闪图
*/
chinese_gif,
CHINESE_GIF,
/**
* 闪图
*/
gif,
spec
GIF,
SPEC
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.bean;
package com.zq.admin.config.bean;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import com.zq.system.exception.BadConfigurationException;
import com.zq.admin.exception.BadConfigurationException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
......@@ -40,19 +40,10 @@ public class LoginProperties {
private LoginCode loginCode;
/**
* 用户登录信息缓存
*/
private boolean cacheEnable;
public boolean isSingleLogin() {
return singleLogin;
}
public boolean isCacheEnable() {
return cacheEnable;
}
/**
* 获取验证码生产类
*
......@@ -62,7 +53,7 @@ public class LoginProperties {
if (Objects.isNull(loginCode)) {
loginCode = new LoginCode();
if (Objects.isNull(loginCode.getCodeType())) {
loginCode.setCodeType(LoginCodeEnum.arithmetic);
loginCode.setCodeType(LoginCodeEnum.ARITHMETIC);
}
}
return switchCaptcha(loginCode);
......@@ -78,25 +69,25 @@ public class LoginProperties {
Captcha captcha;
synchronized (this) {
switch (loginCode.getCodeType()) {
case arithmetic:
case ARITHMETIC:
// 算术类型 https://gitee.com/whvse/EasyCaptcha
captcha = new FixedArithmeticCaptcha(loginCode.getWidth(), loginCode.getHeight());
// 几位数运算,默认是两位
captcha.setLen(loginCode.getLength());
break;
case chinese:
case CHINESE:
captcha = new ChineseCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case chinese_gif:
case CHINESE_GIF:
captcha = new ChineseGifCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case gif:
case GIF:
captcha = new GifCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case spec:
case SPEC:
captcha = new SpecCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
......@@ -111,6 +102,7 @@ public class LoginProperties {
}
static class FixedArithmeticCaptcha extends ArithmeticCaptcha {
public FixedArithmeticCaptcha(int width, int height) {
super(width, height);
}
......@@ -131,5 +123,7 @@ public class LoginProperties {
return chars.toCharArray();
}
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.security;
package com.zq.admin.config.security;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
......@@ -29,9 +29,10 @@ import java.io.IOException;
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
//当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
//当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.security;
package com.zq.admin.config.security;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
......@@ -34,6 +34,7 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException == null ? "Unauthorized" : authException.getMessage());
}
}
......@@ -13,13 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.security;
package com.zq.admin.config.security;
import com.zq.admin.modules.security.service.OnlineUserService;
import com.zq.admin.modules.security.service.UserCacheManager;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.config.security.SecurityProperties;
import com.zq.common.config.security.TokenProvider;
import com.zq.common.utils.RequestMethodEnum;
import com.zq.system.modules.system.service.OnlineUserService;
import com.zq.system.modules.system.service.UserCacheClean;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
......@@ -55,7 +56,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final ApplicationContext applicationContext;
private final SecurityProperties properties;
private final OnlineUserService onlineUserService;
private final UserCacheClean userCacheClean;
private final UserCacheManager userCacheManager;
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
......@@ -105,15 +106,15 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
"/webSocket/**"
).permitAll()
// swagger 文档
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/admin/swagger-ui.html").permitAll()
.antMatchers("/admin/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/*/api-docs").permitAll()
// 文件
.antMatchers("/avatar/**").permitAll()
.antMatchers("/file/**").permitAll()
.antMatchers("/admin/avatar/**").permitAll()
.antMatchers("/admin/file/**").permitAll()
// 阿里巴巴 druid
.antMatchers("/druid/**").permitAll()
.antMatchers("/admin/druid/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型
......@@ -135,11 +136,11 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
}
private TokenConfigurer securityConfigurerAdapter() {
return new TokenConfigurer(tokenProvider, properties, onlineUserService, userCacheClean);
return new TokenConfigurer(tokenProvider, properties, onlineUserService, userCacheManager);
}
private Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
Map<String, Set<String>> anonymousUrls = new HashMap<>(6);
Map<String, Set<String>> anonymousUrls = new HashMap<>(8);
Set<String> get = new HashSet<>();
Set<String> post = new HashSet<>();
Set<String> put = new HashSet<>();
......@@ -182,4 +183,5 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
return anonymousUrls;
}
}
......@@ -13,11 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.security;
package com.zq.admin.config.security;
import com.zq.system.modules.system.service.OnlineUserService;
import com.zq.system.modules.system.service.UserCacheClean;
import com.zq.admin.modules.security.service.OnlineUserService;
import com.zq.admin.modules.security.service.UserCacheManager;
import com.zq.common.config.security.SecurityProperties;
import com.zq.common.config.security.TokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
......@@ -33,11 +34,12 @@ public class TokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFi
private final TokenProvider tokenProvider;
private final SecurityProperties properties;
private final OnlineUserService onlineUserService;
private final UserCacheClean userCacheClean;
private final UserCacheManager userCacheManager;
@Override
public void configure(HttpSecurity http) {
TokenFilter customFilter = new TokenFilter(tokenProvider, properties, onlineUserService, userCacheClean);
TokenFilter customFilter = new TokenFilter(tokenProvider, properties, onlineUserService, userCacheManager);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}
......@@ -13,19 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.config.security;
package com.zq.admin.config.security;
import cn.hutool.core.util.StrUtil;
import com.zq.admin.modules.security.service.OnlineUserService;
import com.zq.admin.modules.security.service.UserCacheManager;
import com.zq.common.config.security.SecurityProperties;
import com.zq.common.config.security.TokenProvider;
import com.zq.common.context.ContextUtils;
import com.zq.common.vo.OnlineUserDto;
import com.zq.system.modules.system.service.OnlineUserService;
import com.zq.system.modules.system.service.UserCacheClean;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
......@@ -40,25 +42,26 @@ import java.util.Objects;
* @author /
*/
public class TokenFilter extends GenericFilterBean {
private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);
private final TokenProvider tokenProvider;
private final SecurityProperties properties;
private final OnlineUserService onlineUserService;
private final UserCacheClean userCacheClean;
private final UserCacheManager userCacheManager;
/**
* @param tokenProvider Token
* @param properties JWT
* @param onlineUserService 用户在线
* @param userCacheClean 用户缓存清理工具
* @param userCacheManager 用户缓存工具
*/
public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService, UserCacheClean userCacheClean) {
public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService, UserCacheManager userCacheManager) {
this.properties = properties;
this.onlineUserService = onlineUserService;
this.tokenProvider = tokenProvider;
this.userCacheClean = userCacheClean;
this.userCacheManager = userCacheManager;
}
@Override
......@@ -77,14 +80,16 @@ public class TokenFilter extends GenericFilterBean {
cleanUserCache = true;
} finally {
if (cleanUserCache || Objects.isNull(onlineUserDto)) {
userCacheClean.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY)));
userCacheManager.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY)));
}
}
if (onlineUserDto != null && StringUtils.isNotBlank(token)) {
if (onlineUserDto != null && StringUtils.hasText(token)) {
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Token 续期
tokenProvider.checkRenewal(token);
ContextUtils.setAdminContext(onlineUserDto);
}
}
filterChain.doFilter(servletRequest, servletResponse);
......
// package com.zq.admin.config.security;/*
// * Copyright 2019-2020 Zheng Jie
// *
// * 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
// *
// * http://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 cn.hutool.core.date.DateField;
// import cn.hutool.core.date.DateUtil;
// import cn.hutool.core.util.IdUtil;
// import com.zq.common.config.redis.RedisUtils;
// import com.zq.common.config.security.SecurityProperties;
// import io.jsonwebtoken.Claims;
// import io.jsonwebtoken.Jwts;
// import io.jsonwebtoken.SignatureAlgorithm;
// import lombok.RequiredArgsConstructor;
// import lombok.extern.slf4j.Slf4j;
// import org.apache.commons.lang3.StringUtils;
// import org.springframework.beans.factory.InitializingBean;
// import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
// import org.springframework.security.core.Authentication;
// import org.springframework.security.core.userdetails.User;
// import org.springframework.stereotype.Component;
//
// import javax.crypto.spec.SecretKeySpec;
// import javax.servlet.http.HttpServletRequest;
// import javax.xml.bind.DatatypeConverter;
// import java.security.Key;
// import java.util.ArrayList;
// import java.util.Date;
// import java.util.concurrent.TimeUnit;
//
// /**
// * @author /
// */
// @Slf4j
// @Component
// @RequiredArgsConstructor
// public class TokenProvider implements InitializingBean {
//
// private final RedisUtils redisUtils;
// private final SecurityProperties properties;
//
// public static final String AUTHORITIES_KEY = "auth";
// private static Key key;
// private static SignatureAlgorithm signatureAlgorithm;
//
// @Override
// public void afterPropertiesSet() {
// signatureAlgorithm = SignatureAlgorithm.HS512;
// byte[] keyBytes = DatatypeConverter.parseBase64Binary(properties.getBase64Secret());
// key = new SecretKeySpec(keyBytes, signatureAlgorithm.getJcaName());
// }
//
// public static String createToken(Authentication authentication) {
// return Jwts.builder()
// .claim(AUTHORITIES_KEY, authentication.getName())
// .setSubject(authentication.getName())
// .signWith(signatureAlgorithm, key)
// // 加入ID确保生成的 Token 都不一致
// .setId(IdUtil.simpleUUID())
// .compact();
// }
//
// public Claims getClaims(String token) {
// return Jwts.parser()
// .setSigningKey(DatatypeConverter.parseBase64Binary(properties.getBase64Secret()))
// .parseClaimsJws(token)
// .getBody();
// }
//
// public Authentication getAuthentication(String token) {
// Claims claims = getClaims(token);
// User principal = new User(claims.getSubject(), "******", new ArrayList<>());
// return new UsernamePasswordAuthenticationToken(principal, token, new ArrayList<>());
// }
//
// /**
// * @param token 需要检查的token
// */
// public void checkRenewal(String token) {
// // 判断是否续期token,计算token的过期时间
// long time = redisUtils.getExpire(properties.getOnlineKey() + token) * 1000;
// Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
// // 判断当前时间与过期时间的时间差
// long differ = expireDate.getTime() - System.currentTimeMillis();
// // 如果在续期检查的范围内,则续期
// if (differ <= properties.getDetect()) {
// long renew = time + properties.getRenew();
// redisUtils.expire(properties.getOnlineKey() + token, renew, TimeUnit.MILLISECONDS);
// }
// }
//
// public String getToken(HttpServletRequest request) {
// String bearerToken = request.getHeader(properties.getHeader());
// if (StringUtils.isBlank(bearerToken)) {
// return null;
// }
// if (bearerToken.startsWith(properties.getTokenStartWith())) {
// // 去掉令牌前缀
// return bearerToken.replace(properties.getTokenStartWith(), "");
// } else {
// log.debug("非法Token:{}", bearerToken);
// }
// return null;
// }
//
// }
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.constant;
/**
* 常用静态常量
*
* @author Zheng Jie
* @date 2018-12-26
*/
public class AdminConstant {
/**
* 用于IP定位转换
*/
public static final String REGION = "内网IP|内网IP";
/**
* win 系统
*/
public static final String WIN = "win";
/**
* mac 系统
*/
public static final String MAC = "mac";
/**
* 常用接口
*/
public static class Url {
// IP归属地查询
public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";
}
}
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.constant.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>
* 验证码业务场景
* </p>
*
* @author Zheng Jie
* @date 2020-05-02
*/
@Getter
@AllArgsConstructor
public enum CodeBiEnum {
/* 旧邮箱修改邮箱 */
ONE(1, "旧邮箱修改邮箱"),
/* 通过邮箱修改密码 */
TWO(2, "通过邮箱修改密码");
private final Integer code;
private final String description;
public static CodeBiEnum find(Integer code) {
for (CodeBiEnum value : CodeBiEnum.values()) {
if (value.getCode().equals(code)) {
return value;
}
}
return null;
}
}
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.constant.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>
* 验证码业务场景对应的 Redis 中的 key
* </p>
*
* @author Zheng Jie
* @date 2020-05-02
*/
@Getter
@AllArgsConstructor
public enum CodeEnum {
/* 通过手机号码重置邮箱 */
PHONE_RESET_EMAIL_CODE("phone_reset_email_code_", "通过手机号码重置邮箱"),
/* 通过旧邮箱重置邮箱 */
EMAIL_RESET_EMAIL_CODE("email_reset_email_code_", "通过旧邮箱重置邮箱"),
/* 通过手机号码重置密码 */
PHONE_RESET_PWD_CODE("phone_reset_pwd_code_", "通过手机号码重置密码"),
/* 通过邮箱重置密码 */
EMAIL_RESET_PWD_CODE("email_reset_pwd_code_", "通过邮箱重置密码");
private final String key;
private final String description;
}
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.constant.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>
* 数据权限枚举
* </p>
*
* @author Zheng Jie
* @date 2020-05-07
*/
@Getter
@AllArgsConstructor
public enum DataScopeEnum {
/* 全部的数据权限 */
ALL("全部", "全部的数据权限"),
/* 自己部门的数据权限 */
THIS_LEVEL("本级", "自己部门的数据权限"),
/* 自定义的数据权限 */
CUSTOMIZE("自定义", "自定义的数据权限");
private final String value;
private final String description;
public static DataScopeEnum find(String val) {
for (DataScopeEnum dataScopeEnum : DataScopeEnum.values()) {
if (dataScopeEnum.getValue().equals(val)) {
return dataScopeEnum;
}
}
return null;
}
}
/*
* Copyright 2019-2020 Zheng Jie
*
* 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
*
* http://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.
*/
package com.zq.admin.constant.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Zheng Jie
* @website https://el-admin.vip
* @description
* @date 2020-06-10
**/
@Getter
@AllArgsConstructor
public enum RequestMethodEnum {
/**
* 搜寻 @AnonymousGetMapping
*/
GET("GET"),
/**
* 搜寻 @AnonymousPostMapping
*/
POST("POST"),
/**
* 搜寻 @AnonymousPutMapping
*/
PUT("PUT"),
/**
* 搜寻 @AnonymousPatchMapping
*/
PATCH("PATCH"),
/**
* 搜寻 @AnonymousDeleteMapping
*/
DELETE("DELETE"),
/**
* 否则就是所有 Request 接口都放行
*/
ALL("All");
/**
* Request 类型
*/
private final String type;
public static RequestMethodEnum find(String type) {
for (RequestMethodEnum value : RequestMethodEnum.values()) {
if (value.getType().equals(type)) {
return value;
}
}
return ALL;
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception;
package com.zq.admin.exception;
/**
* 统一关于错误配置信息 异常
......@@ -22,6 +22,7 @@ package com.zq.system.exception;
* @date: 2020/6/10 18:06
*/
public class BadConfigurationException extends RuntimeException {
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
......@@ -95,4 +96,5 @@ public class BadConfigurationException extends RuntimeException {
protected BadConfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception;
package com.zq.admin.exception;
import lombok.Getter;
import org.springframework.http.HttpStatus;
......@@ -30,12 +30,13 @@ public class BadRequestException extends RuntimeException {
private Integer status = BAD_REQUEST.value();
public BadRequestException(String msg){
public BadRequestException(String msg) {
super(msg);
}
public BadRequestException(HttpStatus status, String msg){
public BadRequestException(HttpStatus status, String msg) {
super(msg);
this.status = status.value();
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception;
package com.zq.admin.exception;
import org.springframework.util.StringUtils;
......@@ -29,6 +29,7 @@ public class EntityExistException extends RuntimeException {
private static String generateMessage(String entity, String field, String val) {
return StringUtils.capitalize(entity)
+ " with " + field + " "+ val + " existed";
+ " with " + field + " " + val + " existed";
}
}
\ No newline at end of file
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception;
package com.zq.admin.exception;
import org.springframework.util.StringUtils;
......@@ -29,6 +29,7 @@ public class EntityNotFoundException extends RuntimeException {
private static String generateMessage(String entity, String field, String val) {
return StringUtils.capitalize(entity)
+ " with " + field + " "+ val + " does not exist";
+ " with " + field + " " + val + " does not exist";
}
}
\ No newline at end of file
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception.handler;
package com.zq.admin.exception.handler;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
......@@ -36,18 +36,19 @@ class ApiError {
timestamp = LocalDateTime.now();
}
public static ApiError error(String message){
public static ApiError error(String message) {
ApiError apiError = new ApiError();
apiError.setMessage(message);
return apiError;
}
public static ApiError error(Integer status, String message){
public static ApiError error(Integer status, String message) {
ApiError apiError = new ApiError();
apiError.setStatus(status);
apiError.setMessage(message);
return apiError;
}
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.exception.handler;
package com.zq.admin.exception.handler;
import com.zq.system.exception.BadRequestException;
import com.zq.system.exception.EntityExistException;
import com.zq.system.exception.EntityNotFoundException;
import com.zq.admin.exception.BadRequestException;
import com.zq.admin.exception.EntityExistException;
import com.zq.admin.exception.EntityNotFoundException;
import com.zq.common.utils.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
......@@ -112,4 +112,5 @@ public class GlobalExceptionHandler {
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
}
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.domain;
package com.zq.admin.modules.generator.domain;
import com.zq.system.modules.generator.utils.GenUtil;
import com.zq.admin.modules.generator.utils.GenUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
......@@ -96,4 +96,5 @@ public class ColumnInfo implements Serializable {
this.listShow = true;
this.formShow = true;
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.domain;
package com.zq.admin.modules.generator.domain;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
......@@ -77,4 +77,5 @@ public class GenConfig implements Serializable {
@ApiModelProperty(value = "是否覆盖")
private Boolean cover = false;
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.domain.vo;
package com.zq.admin.modules.generator.domain.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
......
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.repository;
package com.zq.admin.modules.generator.repository;
import com.zq.system.modules.generator.domain.ColumnInfo;
import com.zq.admin.modules.generator.domain.ColumnInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
......@@ -33,4 +33,5 @@ public interface ColumnInfoRepository extends JpaRepository<ColumnInfo, Long> {
* @return 表信息
*/
List<ColumnInfo> findByTableNameOrderByIdAsc(String tableName);
}
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.repository;
package com.zq.admin.modules.generator.repository;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.domain.GenConfig;
import org.springframework.data.jpa.repository.JpaRepository;
/**
......@@ -31,4 +31,5 @@ public interface GenConfigRepository extends JpaRepository<GenConfig, Long> {
* @return /
*/
GenConfig findByTableName(String tableName);
}
......@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.rest;
package com.zq.admin.modules.generator.rest;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.system.modules.generator.service.GenConfigService;
import com.zq.admin.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.service.GenConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
......@@ -31,7 +31,7 @@ import org.springframework.web.bind.annotation.*;
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/genConfig")
@RequestMapping("/admin/genConfig")
@Api(tags = "系统:代码生成器配置管理")
public class GenConfigController {
......@@ -39,13 +39,14 @@ public class GenConfigController {
@ApiOperation("查询")
@GetMapping(value = "/{tableName}")
public ResponseEntity<Object> query(@PathVariable String tableName) {
public ResponseEntity<Object> queryGenConfig(@PathVariable String tableName) {
return new ResponseEntity<>(genConfigService.find(tableName), HttpStatus.OK);
}
@ApiOperation("修改")
@PutMapping
public ResponseEntity<Object> update(@Validated @RequestBody GenConfig genConfig) {
@ApiOperation("修改")
public ResponseEntity<Object> updateGenConfig(@Validated @RequestBody GenConfig genConfig) {
return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig), HttpStatus.OK);
}
}
......@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.rest;
package com.zq.admin.modules.generator.rest;
import com.zq.system.exception.BadRequestException;
import com.zq.system.modules.generator.domain.ColumnInfo;
import com.zq.system.modules.generator.service.GenConfigService;
import com.zq.system.modules.generator.service.GeneratorService;
import com.zq.system.utils.PageUtil;
import com.zq.admin.exception.BadRequestException;
import com.zq.admin.modules.generator.domain.ColumnInfo;
import com.zq.admin.modules.generator.service.GenConfigService;
import com.zq.admin.modules.generator.service.GeneratorService;
import com.zq.admin.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
......@@ -38,7 +38,7 @@ import java.util.List;
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/generator")
@RequestMapping("/admin/generator")
@Api(tags = "系统:代码生成管理")
public class GeneratorController {
......@@ -50,7 +50,7 @@ public class GeneratorController {
@ApiOperation("查询数据库数据")
@GetMapping(value = "/tables/all")
public ResponseEntity<Object> queryTables() {
public ResponseEntity<Object> queryAllTables() {
return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK);
}
......@@ -72,14 +72,14 @@ public class GeneratorController {
@ApiOperation("保存字段数据")
@PutMapping
public ResponseEntity<HttpStatus> save(@RequestBody List<ColumnInfo> columnInfos) {
public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos) {
generatorService.save(columnInfos);
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("同步字段数据")
@PostMapping(value = "sync")
public ResponseEntity<HttpStatus> sync(@RequestBody List<String> tables) {
public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables) {
for (String table : tables) {
generatorService.sync(generatorService.getColumns(table), generatorService.query(table));
}
......@@ -88,7 +88,7 @@ public class GeneratorController {
@ApiOperation("生成代码")
@PostMapping(value = "/{tableName}/{type}")
public ResponseEntity<Object> generator(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
if (!generatorEnabled && type == 0) {
throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!");
}
......@@ -109,4 +109,5 @@ public class GeneratorController {
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
......@@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.service;
package com.zq.admin.modules.generator.service;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.domain.GenConfig;
/**
* @author Zheng Jie
......@@ -39,4 +39,5 @@ public interface GenConfigService {
* @return 表配置
*/
GenConfig update(String tableName, GenConfig genConfig);
}
......@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.service;
package com.zq.admin.modules.generator.service;
import com.zq.system.modules.generator.domain.ColumnInfo;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.domain.ColumnInfo;
import com.zq.admin.modules.generator.domain.GenConfig;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletRequest;
......@@ -102,4 +102,5 @@ public interface GeneratorService {
* @return /
*/
List<ColumnInfo> query(String table);
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.service.impl;
package com.zq.admin.modules.generator.service.impl;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.system.modules.generator.repository.GenConfigRepository;
import com.zq.system.modules.generator.service.GenConfigService;
import com.zq.admin.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.repository.GenConfigRepository;
import com.zq.admin.modules.generator.service.GenConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
......@@ -64,4 +64,5 @@ public class GenConfigServiceImpl implements GenConfigService {
genConfig.setApiPath(api.toString());
return genConfigRepository.save(genConfig);
}
}
......@@ -13,20 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.service.impl;
package com.zq.admin.modules.generator.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import com.zq.system.exception.BadRequestException;
import com.zq.system.modules.generator.domain.ColumnInfo;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.system.modules.generator.domain.vo.TableInfo;
import com.zq.system.modules.generator.repository.ColumnInfoRepository;
import com.zq.system.modules.generator.service.GeneratorService;
import com.zq.system.modules.generator.utils.GenUtil;
import com.zq.system.utils.FileUtil;
import com.zq.system.utils.PageUtil;
import com.zq.admin.exception.BadRequestException;
import com.zq.admin.modules.generator.domain.ColumnInfo;
import com.zq.admin.modules.generator.domain.GenConfig;
import com.zq.admin.modules.generator.domain.vo.TableInfo;
import com.zq.admin.modules.generator.repository.ColumnInfoRepository;
import com.zq.admin.modules.generator.service.GeneratorService;
import com.zq.admin.modules.generator.utils.GenUtil;
import com.zq.admin.utils.FileUtil;
import com.zq.admin.utils.PageUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -54,6 +54,7 @@ import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {
private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class);
@PersistenceContext
private EntityManager em;
......@@ -203,4 +204,5 @@ public class GeneratorServiceImpl implements GeneratorService {
throw new BadRequestException("打包失败");
}
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.utils;
package com.zq.admin.modules.generator.utils;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
......@@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory;
* @date 2019-01-03
*/
public class ColUtil {
private static final Logger log = LoggerFactory.getLogger(ColUtil.class);
/**
......@@ -53,4 +54,5 @@ public class ColUtil {
}
return null;
}
}
......@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.generator.utils;
package com.zq.admin.modules.generator.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.*;
import com.zq.admin.modules.generator.domain.ColumnInfo;
import com.zq.admin.modules.generator.domain.GenConfig;
import com.zq.admin.utils.FileUtil;
import com.zq.common.utils.CamelNameUtils;
import com.zq.system.modules.generator.domain.ColumnInfo;
import com.zq.system.modules.generator.domain.GenConfig;
import com.zq.system.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
......@@ -35,7 +35,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zq.system.utils.FileUtil.SYS_TEM_DIR;
import static com.zq.admin.utils.FileUtil.SYS_TEM_DIR;
/**
* 代码生成
......@@ -424,4 +424,5 @@ public class GenUtil {
writer.close();
}
}
}
......@@ -13,56 +13,57 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.domain;
package com.zq.admin.modules.mnt.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.zq.admin.base.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_app")
@Table(name = "mnt_app")
public class App extends BaseEntity implements Serializable {
@Id
@Column(name = "app_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "app_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ApiModelProperty(value = "名称")
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "端口")
private int port;
@ApiModelProperty(value = "端口")
private int port;
@ApiModelProperty(value = "上传路径")
private String uploadPath;
@ApiModelProperty(value = "上传路径")
private String uploadPath;
@ApiModelProperty(value = "部署路径")
private String deployPath;
@ApiModelProperty(value = "部署路径")
private String deployPath;
@ApiModelProperty(value = "备份路径")
private String backupPath;
@ApiModelProperty(value = "备份路径")
private String backupPath;
@ApiModelProperty(value = "启动脚本")
private String startScript;
@ApiModelProperty(value = "启动脚本")
private String startScript;
@ApiModelProperty(value = "部署脚本")
private String deployScript;
@ApiModelProperty(value = "部署脚本")
private String deployScript;
public void copy(App source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
public void copy(App source) {
BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
}
}
......@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.domain;
package com.zq.admin.modules.mnt.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.zq.admin.base.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
......@@ -29,33 +29,34 @@ import javax.persistence.Table;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_database")
@Table(name = "mnt_database")
public class Database extends BaseEntity implements Serializable {
@Id
@Column(name = "db_id")
@ApiModelProperty(value = "ID", hidden = true)
@ApiModelProperty(value = "ID", hidden = true)
private String id;
@ApiModelProperty(value = "数据库名称")
@ApiModelProperty(value = "数据库名称")
private String name;
@ApiModelProperty(value = "数据库连接地址")
@ApiModelProperty(value = "数据库连接地址")
private String jdbcUrl;
@ApiModelProperty(value = "数据库密码")
@ApiModelProperty(value = "数据库密码")
private String pwd;
@ApiModelProperty(value = "用户名")
@ApiModelProperty(value = "用户名")
private String userName;
public void copy(Database source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
public void copy(Database source) {
BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
}
}
......@@ -13,48 +13,49 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.domain;
package com.zq.admin.modules.mnt.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.zq.admin.base.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_deploy")
@Table(name = "mnt_deploy")
public class Deploy extends BaseEntity implements Serializable {
@Id
@Column(name = "deploy_id")
@ApiModelProperty(value = "ID", hidden = true)
@Column(name = "deploy_id")
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@ApiModelProperty(name = "服务器", hidden = true)
@JoinTable(name = "mnt_deploy_server",
joinColumns = {@JoinColumn(name = "deploy_id",referencedColumnName = "deploy_id")},
inverseJoinColumns = {@JoinColumn(name = "server_id",referencedColumnName = "server_id")})
private Set<ServerDeploy> deploys;
@ManyToMany
@ApiModelProperty(name = "服务器", hidden = true)
@JoinTable(name = "mnt_deploy_server",
joinColumns = {@JoinColumn(name = "deploy_id", referencedColumnName = "deploy_id")},
inverseJoinColumns = {@JoinColumn(name = "server_id", referencedColumnName = "server_id")})
private Set<ServerDeploy> deploys;
@ManyToOne
@ManyToOne
@JoinColumn(name = "app_id")
@ApiModelProperty(value = "应用编号")
@ApiModelProperty(value = "应用编号")
private App app;
public void copy(Deploy source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
public void copy(Deploy source) {
BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.domain;
package com.zq.admin.modules.mnt.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
......@@ -30,37 +30,38 @@ import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_deploy_history")
@Table(name = "mnt_deploy_history")
public class DeployHistory implements Serializable {
@Id
@Column(name = "history_id")
@ApiModelProperty(value = "ID", hidden = true)
@ApiModelProperty(value = "ID", hidden = true)
private String id;
@ApiModelProperty(value = "应用名称")
private String appName;
@ApiModelProperty(value = "IP")
@ApiModelProperty(value = "IP")
private String ip;
@CreationTimestamp
@ApiModelProperty(value = "部署时间")
@CreationTimestamp
@ApiModelProperty(value = "部署时间")
private Timestamp deployDate;
@ApiModelProperty(value = "部署者")
@ApiModelProperty(value = "部署者")
private String deployUser;
@ApiModelProperty(value = "部署ID")
private Long deployId;
@ApiModelProperty(value = "部署ID")
private Long deployId;
public void copy(DeployHistory source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
public void copy(DeployHistory source) {
BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
}
}
......@@ -13,27 +13,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.domain;
package com.zq.admin.modules.mnt.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.zq.admin.base.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseEntity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Entity
@Getter
@Setter
@Table(name="mnt_server")
@Table(name = "mnt_server")
public class ServerDeploy extends BaseEntity implements Serializable {
@Id
......@@ -57,8 +57,8 @@ public class ServerDeploy extends BaseEntity implements Serializable {
@ApiModelProperty(value = "密码")
private String password;
public void copy(ServerDeploy source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
public void copy(ServerDeploy source) {
BeanUtil.copyProperties(source, this, CopyOptions.create().setIgnoreNullValue(true));
}
@Override
......@@ -78,4 +78,5 @@ public class ServerDeploy extends BaseEntity implements Serializable {
public int hashCode() {
return Objects.hash(id, name);
}
}
......@@ -13,15 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.repository;
package com.zq.admin.modules.mnt.repository;
import com.zq.system.modules.mnt.domain.App;
import com.zq.admin.modules.mnt.domain.App;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface AppRepository extends JpaRepository<App, Long>, JpaSpecificationExecutor<App> {
}
......@@ -13,15 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.repository;
package com.zq.admin.modules.mnt.repository;
import com.zq.system.modules.mnt.domain.Database;
import com.zq.admin.modules.mnt.domain.Database;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface DatabaseRepository extends JpaRepository<Database, String>, JpaSpecificationExecutor<Database> {
}
......@@ -13,15 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.repository;
package com.zq.admin.modules.mnt.repository;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployHistoryRepository extends JpaRepository<DeployHistory, String>, JpaSpecificationExecutor<DeployHistory> {
}
......@@ -13,15 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.repository;
package com.zq.admin.modules.mnt.repository;
import com.zq.system.modules.mnt.domain.Deploy;
import com.zq.admin.modules.mnt.domain.Deploy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployRepository extends JpaRepository<Deploy, Long>, JpaSpecificationExecutor<Deploy> {
}
......@@ -13,22 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.repository;
package com.zq.admin.modules.mnt.repository;
import com.zq.system.modules.mnt.domain.ServerDeploy;
import com.zq.admin.modules.mnt.domain.ServerDeploy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface ServerDeployRepository extends JpaRepository<ServerDeploy, Long>, JpaSpecificationExecutor<ServerDeploy> {
/**
* 根据IP查询
*
* @param ip /
* @return /
*/
ServerDeploy findByIp(String ip);
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.rest;
package com.zq.admin.modules.mnt.rest;
import com.zq.system.modules.mnt.domain.App;
import com.zq.system.modules.mnt.service.AppService;
import com.zq.system.modules.mnt.service.dto.AppQueryCriteria;
import com.zq.admin.modules.mnt.domain.App;
import com.zq.admin.modules.mnt.service.AppService;
import com.zq.admin.modules.mnt.service.dto.AppQueryCriteria;
import com.zq.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......@@ -40,7 +40,7 @@ import java.util.Set;
@RestController
@RequiredArgsConstructor
@Api(tags = "运维:应用管理")
@RequestMapping("/sys/app")
@RequestMapping("/admin/app")
public class AppController {
private final AppService appService;
......@@ -48,14 +48,14 @@ public class AppController {
@ApiOperation("导出应用数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('app:list')")
public void download(HttpServletResponse response, AppQueryCriteria criteria) throws IOException {
public void exportApp(HttpServletResponse response, AppQueryCriteria criteria) throws IOException {
appService.download(appService.queryAll(criteria), response);
}
@ApiOperation(value = "查询应用")
@GetMapping
@PreAuthorize("@el.check('app:list')")
public ResponseEntity<Object> query(AppQueryCriteria criteria, Pageable pageable) {
public ResponseEntity<Object> queryApp(AppQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(appService.queryAll(criteria, pageable), HttpStatus.OK);
}
......@@ -63,7 +63,7 @@ public class AppController {
@ApiOperation(value = "新增应用")
@PostMapping
@PreAuthorize("@el.check('app:add')")
public ResponseEntity<Object> create(@Validated @RequestBody App resources) {
public ResponseEntity<Object> createApp(@Validated @RequestBody App resources) {
appService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
......@@ -72,7 +72,7 @@ public class AppController {
@ApiOperation(value = "修改应用")
@PutMapping
@PreAuthorize("@el.check('app:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody App resources) {
public ResponseEntity<Object> updateApp(@Validated @RequestBody App resources) {
appService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
......@@ -81,8 +81,9 @@ public class AppController {
@ApiOperation(value = "删除应用")
@DeleteMapping
@PreAuthorize("@el.check('app:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
public ResponseEntity<Object> deleteApp(@RequestBody Set<Long> ids) {
appService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.rest;
package com.zq.admin.modules.mnt.rest;
import com.zq.admin.exception.BadRequestException;
import com.zq.admin.modules.mnt.domain.Database;
import com.zq.admin.modules.mnt.service.DatabaseService;
import com.zq.admin.modules.mnt.service.dto.DatabaseDto;
import com.zq.admin.modules.mnt.service.dto.DatabaseQueryCriteria;
import com.zq.admin.modules.mnt.util.SqlUtils;
import com.zq.admin.utils.FileUtil;
import com.zq.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.zq.system.exception.BadRequestException;
import com.zq.system.modules.mnt.domain.Database;
import com.zq.system.modules.mnt.service.DatabaseService;
import com.zq.system.modules.mnt.service.dto.DatabaseDto;
import com.zq.system.modules.mnt.service.dto.DatabaseQueryCriteria;
import com.zq.system.modules.mnt.util.SqlUtils;
import com.zq.system.utils.FileUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -41,46 +41,46 @@ import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Api(tags = "运维:数据库管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/database")
@RequestMapping("/admin/database")
public class DatabaseController {
private final String fileSavePath = FileUtil.getTmpDirPath()+"/";
private final String fileSavePath = FileUtil.getTmpDirPath() + "/";
private final DatabaseService databaseService;
@ApiOperation("导出数据库数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void download(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException {
databaseService.download(databaseService.queryAll(criteria), response);
}
@ApiOperation("导出数据库数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void exportDatabase(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException {
databaseService.download(databaseService.queryAll(criteria), response);
}
@ApiOperation(value = "查询数据库")
@GetMapping
@PreAuthorize("@el.check('database:list')")
public ResponseEntity<Object> query(DatabaseQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(databaseService.queryAll(criteria,pageable), HttpStatus.OK);
@PreAuthorize("@el.check('database:list')")
public ResponseEntity<Object> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(databaseService.queryAll(criteria, pageable), HttpStatus.OK);
}
@Log("新增数据库")
@ApiOperation(value = "新增数据库")
@PostMapping
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Database resources){
databaseService.create(resources);
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources) {
databaseService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改数据库")
@ApiOperation(value = "修改数据库")
@PutMapping
@PreAuthorize("@el.check('database:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody Database resources){
@PreAuthorize("@el.check('database:edit')")
public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources) {
databaseService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
......@@ -88,37 +88,38 @@ public class DatabaseController {
@Log("删除数据库")
@ApiOperation(value = "删除数据库")
@DeleteMapping
@PreAuthorize("@el.check('database:del')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids){
@PreAuthorize("@el.check('database:del')")
public ResponseEntity<Object> deleteDatabase(@RequestBody Set<String> ids) {
databaseService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试数据库链接")
@ApiOperation(value = "测试数据库链接")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('database:testConnect')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){
return new ResponseEntity<>(databaseService.testConnection(resources), HttpStatus.CREATED);
}
@Log("测试数据库链接")
@ApiOperation(value = "测试数据库链接")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('database:testConnect')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources) {
return new ResponseEntity<>(databaseService.testConnection(resources), HttpStatus.CREATED);
}
@Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
String id = request.getParameter("id");
DatabaseDto database = databaseService.findById(id);
String fileName;
if (database != null) {
fileName = file.getOriginalFilename();
File executeFile = new File(fileSavePath + fileName);
FileUtil.del(executeFile);
file.transferTo(executeFile);
String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
return new ResponseEntity<>(result, HttpStatus.OK);
} else {
throw new BadRequestException("Database not exist");
}
}
@Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception {
String id = request.getParameter("id");
DatabaseDto database = databaseService.findById(id);
String fileName;
if(database != null){
fileName = file.getOriginalFilename();
File executeFile = new File(fileSavePath+fileName);
FileUtil.del(executeFile);
file.transferTo(executeFile);
String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
return new ResponseEntity<>(result, HttpStatus.OK);
}else{
throw new BadRequestException("Database not exist");
}
}
}
......@@ -13,17 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.rest;
package com.zq.admin.modules.mnt.rest;
import com.zq.system.modules.mnt.domain.Deploy;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.system.modules.mnt.service.DeployService;
import com.zq.admin.modules.mnt.domain.Deploy;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.service.DeployService;
import com.zq.admin.modules.mnt.service.dto.DeployQueryCriteria;
import com.zq.admin.utils.FileUtil;
import com.zq.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.zq.logging.annotation.Log;
import com.zq.system.modules.mnt.service.dto.DeployQueryCriteria;
import com.zq.system.utils.FileUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -42,113 +42,118 @@ import java.util.Objects;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@Api(tags = "运维:部署管理")
@RequiredArgsConstructor
@RequestMapping("/sys/deploy")
@RequestMapping("/admin/deploy")
public class DeployController {
private final String fileSavePath = FileUtil.getTmpDirPath()+"/";
private final String fileSavePath = FileUtil.getTmpDirPath() + "/";
private final DeployService deployService;
@ApiOperation("导出部署数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void download(HttpServletResponse response, DeployQueryCriteria criteria) throws IOException {
deployService.download(deployService.queryAll(criteria), response);
}
@ApiOperation("导出部署数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('database:list')")
public void exportDeployData(HttpServletResponse response, DeployQueryCriteria criteria) throws IOException {
deployService.download(deployService.queryAll(criteria), response);
}
@ApiOperation(value = "查询部署")
@GetMapping
@PreAuthorize("@el.check('deploy:list')")
public ResponseEntity<Object> query(DeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(deployService.queryAll(criteria,pageable), HttpStatus.OK);
@PreAuthorize("@el.check('deploy:list')")
public ResponseEntity<Object> queryDeployData(DeployQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(deployService.queryAll(criteria, pageable), HttpStatus.OK);
}
@Log("新增部署")
@ApiOperation(value = "新增部署")
@PostMapping
@PreAuthorize("@el.check('deploy:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Deploy resources){
deployService.create(resources);
@PreAuthorize("@el.check('deploy:add')")
public ResponseEntity<Object> createDeploy(@Validated @RequestBody Deploy resources) {
deployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改部署")
@ApiOperation(value = "修改部署")
@PutMapping
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody Deploy resources){
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> updateDeploy(@Validated @RequestBody Deploy resources) {
deployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除部署")
@ApiOperation(value = "删除部署")
@DeleteMapping
@PreAuthorize("@el.check('deploy:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception {
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if(file != null){
fileName = file.getOriginalFilename();
File deployFile = new File(fileSavePath+fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath+fileName ,id);
}else{
System.out.println("没有找到相对应的文件");
}
System.out.println("文件上传的原名称为:"+ Objects.requireNonNull(file).getOriginalFilename());
Map<String, Object> map = new HashMap<>(2);
map.put("errno",0);
map.put("id",fileName);
return new ResponseEntity<>(map, HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){
String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){
String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){
String result = deployService.startServer(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("删除部署")
@ApiOperation(value = "删除部署")
@DeleteMapping
@PreAuthorize("@el.check('deploy:del')")
public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids) {
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if (file != null) {
fileName = file.getOriginalFilename();
File deployFile = new File(fileSavePath + fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath + fileName, id);
} else {
System.out.println("没有找到相对应的文件");
}
System.out.println("文件上传的原名称为:" + Objects.requireNonNull(file).getOriginalFilename());
Map<String, Object> map = new HashMap<>(2);
map.put("errno", 0);
map.put("id", fileName);
return new ResponseEntity<>(map, HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources) {
String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources) {
String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources) {
String result = deployService.startServer(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources) {
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
......@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.rest;
package com.zq.admin.modules.mnt.rest;
import com.zq.admin.modules.mnt.service.DeployHistoryService;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import com.zq.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.zq.logging.annotation.Log;
import com.zq.system.modules.mnt.service.DeployHistoryService;
import com.zq.system.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -32,13 +32,13 @@ import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "运维:部署历史管理")
@RequestMapping("/sys/deployHistory")
@RequestMapping("/admin/deployHistory")
public class DeployHistoryController {
private final DeployHistoryService deployhistoryService;
......@@ -46,23 +46,24 @@ public class DeployHistoryController {
@ApiOperation("导出部署历史数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('deployHistory:list')")
public void download(HttpServletResponse response, DeployHistoryQueryCriteria criteria) throws IOException {
public void exportDeployHistory(HttpServletResponse response, DeployHistoryQueryCriteria criteria) throws IOException {
deployhistoryService.download(deployhistoryService.queryAll(criteria), response);
}
@ApiOperation(value = "查询部署历史")
@GetMapping
@PreAuthorize("@el.check('deployHistory:list')")
public ResponseEntity<Object> query(DeployHistoryQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(deployhistoryService.queryAll(criteria,pageable), HttpStatus.OK);
@PreAuthorize("@el.check('deployHistory:list')")
public ResponseEntity<Object> queryDeployHistory(DeployHistoryQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(deployhistoryService.queryAll(criteria, pageable), HttpStatus.OK);
}
@Log("删除DeployHistory")
@ApiOperation(value = "删除部署历史")
@DeleteMapping
@DeleteMapping
@PreAuthorize("@el.check('deployHistory:del')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids){
public ResponseEntity<Object> deleteDeployHistory(@RequestBody Set<String> ids) {
deployhistoryService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
......@@ -13,15 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.rest;
package com.zq.admin.modules.mnt.rest;
import com.zq.system.modules.mnt.domain.ServerDeploy;
import com.zq.system.modules.mnt.service.ServerDeployService;
import com.zq.system.modules.mnt.service.dto.ServerDeployQueryCriteria;
import com.zq.admin.modules.mnt.domain.ServerDeploy;
import com.zq.admin.modules.mnt.service.ServerDeployService;
import com.zq.admin.modules.mnt.service.dto.ServerDeployQueryCriteria;
import com.zq.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.zq.logging.annotation.Log;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -34,13 +34,13 @@ import java.io.IOException;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@RestController
@Api(tags = "运维:服务器管理")
@RequiredArgsConstructor
@RequestMapping("/sys/serverDeploy")
@RequestMapping("/admin/serverDeploy")
public class ServerDeployController {
private final ServerDeployService serverDeployService;
......@@ -48,22 +48,22 @@ public class ServerDeployController {
@ApiOperation("导出服务器数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('serverDeploy:list')")
public void download(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException {
public void exportServerDeploy(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException {
serverDeployService.download(serverDeployService.queryAll(criteria), response);
}
@ApiOperation(value = "查询服务器")
@GetMapping
@PreAuthorize("@el.check('serverDeploy:list')")
public ResponseEntity<Object> query(ServerDeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable), HttpStatus.OK);
@PreAuthorize("@el.check('serverDeploy:list')")
public ResponseEntity<Object> queryServerDeploy(ServerDeployQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(serverDeployService.queryAll(criteria, pageable), HttpStatus.OK);
}
@Log("新增服务器")
@ApiOperation(value = "新增服务器")
@PostMapping
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> create(@Validated @RequestBody ServerDeploy resources){
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources) {
serverDeployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
......@@ -71,26 +71,27 @@ public class ServerDeployController {
@Log("修改服务器")
@ApiOperation(value = "修改服务器")
@PutMapping
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody ServerDeploy resources){
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources) {
serverDeployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除服务器")
@ApiOperation(value = "删除Server")
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids) {
serverDeployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody ServerDeploy resources){
return new ResponseEntity<>(serverDeployService.testConnect(resources), HttpStatus.CREATED);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources) {
return new ResponseEntity<>(serverDeployService.testConnect(resources), HttpStatus.CREATED);
}
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service;
package com.zq.admin.modules.mnt.service;
import com.zq.system.modules.mnt.domain.App;
import com.zq.system.modules.mnt.service.dto.AppDto;
import com.zq.system.modules.mnt.service.dto.AppQueryCriteria;
import com.zq.admin.modules.mnt.domain.App;
import com.zq.admin.modules.mnt.service.dto.AppDto;
import com.zq.admin.modules.mnt.service.dto.AppQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
......@@ -26,13 +26,14 @@ import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface AppService {
/**
* 分页查询
*
* @param criteria 条件
* @param pageable 分页参数
* @return /
......@@ -41,6 +42,7 @@ public interface AppService {
/**
* 查询全部数据
*
* @param criteria 条件
* @return /
*/
......@@ -48,6 +50,7 @@ public interface AppService {
/**
* 根据ID查询
*
* @param id /
* @return /
*/
......@@ -55,27 +58,32 @@ public interface AppService {
/**
* 创建
*
* @param resources /
*/
void create(App resources);
/**
* 编辑
*
* @param resources /
*/
void update(App resources);
/**
* 删除
*
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 导出数据
*
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException;
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service;
package com.zq.admin.modules.mnt.service;
import com.zq.system.modules.mnt.domain.Database;
import com.zq.system.modules.mnt.service.dto.DatabaseDto;
import com.zq.system.modules.mnt.service.dto.DatabaseQueryCriteria;
import com.zq.admin.modules.mnt.domain.Database;
import com.zq.admin.modules.mnt.service.dto.DatabaseDto;
import com.zq.admin.modules.mnt.service.dto.DatabaseQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
......@@ -33,6 +33,7 @@ public interface DatabaseService {
/**
* 分页查询
*
* @param criteria 条件
* @param pageable 分页参数
* @return /
......@@ -41,6 +42,7 @@ public interface DatabaseService {
/**
* 查询全部
*
* @param criteria 条件
* @return /
*/
......@@ -48,6 +50,7 @@ public interface DatabaseService {
/**
* 根据ID查询
*
* @param id /
* @return /
*/
......@@ -55,34 +58,40 @@ public interface DatabaseService {
/**
* 创建
*
* @param resources /
*/
void create(Database resources);
/**
* 编辑
*
* @param resources /
*/
void update(Database resources);
/**
* 删除
*
* @param ids /
*/
void delete(Set<String> ids);
/**
* 测试连接数据库
* @param resources /
* @return /
*/
boolean testConnection(Database resources);
/**
* 测试连接数据库
*
* @param resources /
* @return /
*/
boolean testConnection(Database resources);
/**
* 导出数据
*
* @param queryAll /
* @param response /
* @throws IOException e
*/
void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException;
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service;
package com.zq.admin.modules.mnt.service;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.system.modules.mnt.service.dto.DeployHistoryDto;
import com.zq.system.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryDto;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
......@@ -32,6 +32,7 @@ public interface DeployHistoryService {
/**
* 分页查询
*
* @param criteria 条件
* @param pageable 分页参数
* @return /
......@@ -40,6 +41,7 @@ public interface DeployHistoryService {
/**
* 查询全部
*
* @param criteria 条件
* @return /
*/
......@@ -47,6 +49,7 @@ public interface DeployHistoryService {
/**
* 根据ID查询
*
* @param id /
* @return /
*/
......@@ -54,21 +57,25 @@ public interface DeployHistoryService {
/**
* 创建
*
* @param resources /
*/
void create(DeployHistory resources);
/**
* 删除
*
* @param ids /
*/
void delete(Set<String> ids);
/**
* 导出数据
*
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException;
}
......@@ -13,12 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service;
package com.zq.admin.modules.mnt.service;
import com.zq.system.modules.mnt.domain.Deploy;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.system.modules.mnt.service.dto.DeployDto;
import com.zq.system.modules.mnt.service.dto.DeployQueryCriteria;
import com.zq.admin.modules.mnt.domain.Deploy;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.service.dto.DeployDto;
import com.zq.admin.modules.mnt.service.dto.DeployQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
......@@ -27,13 +27,14 @@ import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface DeployService {
/**
* 分页查询
*
* @param criteria 条件
* @param pageable 分页参数
* @return /
......@@ -42,6 +43,7 @@ public interface DeployService {
/**
* 查询全部数据
*
* @param criteria 条件
* @return /
*/
......@@ -49,6 +51,7 @@ public interface DeployService {
/**
* 根据ID查询
*
* @param id /
* @return /
*/
......@@ -56,6 +59,7 @@ public interface DeployService {
/**
* 创建
*
* @param resources /
*/
void create(Deploy resources);
......@@ -63,37 +67,45 @@ public interface DeployService {
/**
* 编辑
*
* @param resources /
*/
void update(Deploy resources);
/**
* 删除
*
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 部署文件到服务器
* @param fileSavePath 文件路径
* @param appId 应用ID
/**
* 部署文件到服务器
*
* @param fileSavePath 文件路径
* @param appId 应用ID
*/
void deploy(String fileSavePath, Long appId);
void deploy(String fileSavePath, Long appId);
/**
* 查询部署状态
*
* @param resources /
* @return /
*/
String serverStatus(Deploy resources);
/**
* 启动服务
*
* @param resources /
* @return /
*/
String startServer(Deploy resources);
/**
* 停止服务
*
* @param resources /
* @return /
*/
......@@ -101,6 +113,7 @@ public interface DeployService {
/**
* 停止服务
*
* @param resources /
* @return /
*/
......@@ -108,9 +121,11 @@ public interface DeployService {
/**
* 导出数据
*
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException;
}
......@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service;
package com.zq.admin.modules.mnt.service;
import com.zq.system.modules.mnt.domain.ServerDeploy;
import com.zq.system.modules.mnt.service.dto.ServerDeployDto;
import com.zq.system.modules.mnt.service.dto.ServerDeployQueryCriteria;
import com.zq.admin.modules.mnt.domain.ServerDeploy;
import com.zq.admin.modules.mnt.service.dto.ServerDeployDto;
import com.zq.admin.modules.mnt.service.dto.ServerDeployQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
......@@ -26,13 +26,14 @@ import java.util.List;
import java.util.Set;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
public interface ServerDeployService {
/**
* 分页查询
*
* @param criteria 条件
* @param pageable 分页参数
* @return /
......@@ -41,6 +42,7 @@ public interface ServerDeployService {
/**
* 查询全部数据
*
* @param criteria 条件
* @return /
*/
......@@ -48,6 +50,7 @@ public interface ServerDeployService {
/**
* 根据ID查询
*
* @param id /
* @return /
*/
......@@ -55,41 +58,48 @@ public interface ServerDeployService {
/**
* 创建
*
* @param resources /
*/
void create(ServerDeploy resources);
/**
* 编辑
*
* @param resources /
*/
void update(ServerDeploy resources);
/**
* 删除
*
* @param ids /
*/
void delete(Set<Long> ids);
/**
* 根据IP查询
*
* @param ip /
* @return /
*/
ServerDeployDto findByIp(String ip);
/**
* 测试登录服务器
* @param resources /
* @return /
*/
Boolean testConnect(ServerDeploy resources);
/**
* 测试登录服务器
*
* @param resources /
* @return /
*/
Boolean testConnect(ServerDeploy resources);
/**
* 导出数据
*
* @param queryAll /
* @param response /
* @throws IOException /
*/
void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException;
}
......@@ -13,60 +13,60 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.base.BaseDTO;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseDTO;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class AppDto extends BaseDTO implements Serializable {
/**
* 应用编号
*/
/**
* 应用编号
*/
private Long id;
/**
* 应用名称
*/
private String name;
/**
* 应用名称
*/
private String name;
/**
* 端口
*/
private Integer port;
/**
* 端口
*/
private Integer port;
/**
* 上传目录
*/
private String uploadPath;
/**
* 上传目录
*/
private String uploadPath;
/**
* 部署目录
*/
private String deployPath;
/**
* 部署目录
*/
private String deployPath;
/**
* 备份目录
*/
private String backupPath;
/**
* 备份目录
*/
private String backupPath;
/**
* 启动脚本
*/
private String startScript;
/**
* 启动脚本
*/
private String startScript;
/**
* 部署脚本
*/
private String deployScript;
/**
* 部署脚本
*/
private String deployScript;
}
......@@ -13,27 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.system.annotation.Query;
import com.zq.admin.annotation.Query;
import lombok.Data;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class AppQueryCriteria{
public class AppQueryCriteria {
/**
* 模糊
*/
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE)
private String name;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}
......@@ -13,44 +13,45 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.base.BaseDTO;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseDTO;
import java.io.Serializable;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class DatabaseDto extends BaseDTO implements Serializable {
/**
* id
*/
/**
* id
*/
private String id;
/**
* 数据库名称
*/
/**
* 数据库名称
*/
private String name;
/**
* 数据库连接地址
*/
/**
* 数据库连接地址
*/
private String jdbcUrl;
/**
* 数据库密码
*/
/**
* 数据库密码
*/
private String pwd;
/**
* 用户名
*/
/**
* 用户名
*/
private String userName;
}
......@@ -13,33 +13,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.annotation.Query;
import lombok.Data;
import com.zq.system.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DatabaseQueryCriteria{
public class DatabaseQueryCriteria {
/**
* 模糊
*/
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE)
private String name;
/**
* 精确
*/
/**
* 精确
*/
@Query
private String jdbcUrl;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}
......@@ -13,12 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import cn.hutool.core.collection.CollectionUtil;
import com.zq.admin.base.BaseDTO;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseDTO;
import java.io.Serializable;
import java.util.Objects;
......@@ -27,53 +27,54 @@ import java.util.stream.Collectors;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class DeployDto extends BaseDTO implements Serializable {
/**
* 部署编号
*/
/**
* 部署编号
*/
private String id;
private AppDto app;
private AppDto app;
/**
* 服务器
*/
private Set<ServerDeployDto> deploys;
/**
* 服务器
*/
private Set<ServerDeployDto> deploys;
private String servers;
private String servers;
/**
* 服务状态
*/
private String status;
/**
* 服务状态
*/
private String status;
public String getServers() {
if (CollectionUtil.isNotEmpty(deploys)) {
return deploys.stream().map(ServerDeployDto::getName).collect(Collectors.joining(","));
}
return servers;
}
public String getServers() {
if(CollectionUtil.isNotEmpty(deploys)){
return deploys.stream().map(ServerDeployDto::getName).collect(Collectors.joining(","));
}
return servers;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeployDto deployDto = (DeployDto) o;
return Objects.equals(id, deployDto.id);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeployDto deployDto = (DeployDto) o;
return Objects.equals(id, deployDto.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import lombok.Data;
......@@ -21,39 +21,40 @@ import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployHistoryDto implements Serializable {
/**
* 编号
*/
/**
* 编号
*/
private String id;
/**
* 应用名称
*/
/**
* 应用名称
*/
private String appName;
/**
* 部署IP
*/
/**
* 部署IP
*/
private String ip;
/**
* 部署时间
*/
private Timestamp deployDate;
/**
* 部署时间
*/
private Timestamp deployDate;
/**
* 部署人员
*/
private String deployUser;
/**
* 部署人员
*/
private String deployUser;
/**
* 部署编号
*/
private Long deployId;
/**
* 部署编号
*/
private Long deployId;
}
......@@ -13,30 +13,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.annotation.Query;
import lombok.Data;
import com.zq.system.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployHistoryQueryCriteria{
public class DeployHistoryQueryCriteria {
/**
* 精确
*/
@Query(blurry = "appName,ip,deployUser")
private String blurry;
/**
* 精确
*/
@Query(blurry = "appName,ip,deployUser")
private String blurry;
@Query
private Long deployId;
@Query
private Long deployId;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> deployDate;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> deployDate;
}
......@@ -13,28 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.system.annotation.Query;
import com.zq.admin.annotation.Query;
import lombok.Data;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class DeployQueryCriteria{
public class DeployQueryCriteria {
/**
* 模糊
*/
/**
* 模糊
*/
@Query(type = Query.Type.INNER_LIKE, propName = "name", joinName = "app")
private String appName;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}
......@@ -13,50 +13,51 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.base.BaseDTO;
import lombok.Getter;
import lombok.Setter;
import com.zq.system.base.BaseDTO;
import java.io.Serializable;
import java.util.Objects;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Getter
@Setter
public class ServerDeployDto extends BaseDTO implements Serializable {
private Long id;
private String name;
private String name;
private String ip;
private String ip;
private Integer port;
private Integer port;
private String account;
private String account;
private String password;
private String password;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServerDeployDto that = (ServerDeployDto) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServerDeployDto that = (ServerDeployDto) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
......@@ -13,27 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.dto;
package com.zq.admin.modules.mnt.service.dto;
import com.zq.admin.annotation.Query;
import lombok.Data;
import com.zq.system.annotation.Query;
import java.sql.Timestamp;
import java.util.List;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Data
public class ServerDeployQueryCriteria{
public class ServerDeployQueryCriteria {
/**
* 模糊
*/
@Query(blurry = "name,ip,account")
/**
* 模糊
*/
@Query(blurry = "name,ip,account")
private String blurry;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.impl;
package com.zq.admin.modules.mnt.service.impl;
import com.zq.system.exception.BadRequestException;
import com.zq.system.modules.mnt.domain.App;
import com.zq.system.modules.mnt.repository.AppRepository;
import com.zq.system.modules.mnt.service.AppService;
import com.zq.system.modules.mnt.service.dto.AppDto;
import com.zq.system.modules.mnt.service.dto.AppQueryCriteria;
import com.zq.system.modules.mnt.service.mapstruct.AppMapper;
import com.zq.system.utils.FileUtil;
import com.zq.system.utils.PageUtil;
import com.zq.system.utils.QueryHelp;
import com.zq.system.utils.ValidationUtil;
import com.zq.admin.exception.BadRequestException;
import com.zq.admin.modules.mnt.domain.App;
import com.zq.admin.modules.mnt.repository.AppRepository;
import com.zq.admin.modules.mnt.service.AppService;
import com.zq.admin.modules.mnt.service.dto.AppDto;
import com.zq.admin.modules.mnt.service.dto.AppQueryCriteria;
import com.zq.admin.modules.mnt.service.mapstruct.AppMapper;
import com.zq.admin.utils.FileUtil;
import com.zq.admin.utils.PageUtil;
import com.zq.admin.utils.QueryHelp;
import com.zq.admin.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
......@@ -121,4 +121,5 @@ public class AppServiceImpl implements AppService {
}
FileUtil.downloadExcel(list, response);
}
}
......@@ -13,22 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.impl;
package com.zq.admin.modules.mnt.service.impl;
import cn.hutool.core.util.IdUtil;
import com.zq.admin.modules.mnt.domain.Database;
import com.zq.admin.modules.mnt.repository.DatabaseRepository;
import com.zq.admin.modules.mnt.service.DatabaseService;
import com.zq.admin.modules.mnt.service.dto.DatabaseDto;
import com.zq.admin.modules.mnt.service.dto.DatabaseQueryCriteria;
import com.zq.admin.modules.mnt.service.mapstruct.DatabaseMapper;
import com.zq.admin.modules.mnt.util.SqlUtils;
import com.zq.admin.utils.FileUtil;
import com.zq.admin.utils.PageUtil;
import com.zq.admin.utils.QueryHelp;
import com.zq.admin.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.zq.system.modules.mnt.domain.Database;
import com.zq.system.modules.mnt.repository.DatabaseRepository;
import com.zq.system.modules.mnt.service.DatabaseService;
import com.zq.system.modules.mnt.service.dto.DatabaseDto;
import com.zq.system.modules.mnt.service.dto.DatabaseQueryCriteria;
import com.zq.system.modules.mnt.service.mapstruct.DatabaseMapper;
import com.zq.system.modules.mnt.util.SqlUtils;
import com.zq.system.utils.FileUtil;
import com.zq.system.utils.PageUtil;
import com.zq.system.utils.QueryHelp;
import com.zq.system.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
......@@ -39,9 +39,9 @@ import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Slf4j
@Service
@RequiredArgsConstructor
......@@ -51,20 +51,20 @@ public class DatabaseServiceImpl implements DatabaseService {
private final DatabaseMapper databaseMapper;
@Override
public Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable){
Page<Database> page = databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Object queryAll(DatabaseQueryCriteria criteria, Pageable pageable) {
Page<Database> page = databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(databaseMapper::toDto));
}
@Override
public List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria){
return databaseMapper.toDto(databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<DatabaseDto> queryAll(DatabaseQueryCriteria criteria) {
return databaseMapper.toDto(databaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
public DatabaseDto findById(String id) {
Database database = databaseRepository.findById(id).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",id);
ValidationUtil.isNull(database.getId(), "Database", "id", id);
return databaseMapper.toDto(database);
}
......@@ -79,7 +79,7 @@ public class DatabaseServiceImpl implements DatabaseService {
@Transactional(rollbackFor = Exception.class)
public void update(Database resources) {
Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",resources.getId());
ValidationUtil.isNull(database.getId(), "Database", "id", resources.getId());
database.copy(resources);
databaseRepository.save(database);
}
......@@ -92,15 +92,15 @@ public class DatabaseServiceImpl implements DatabaseService {
}
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
@Override
public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException {
......@@ -115,4 +115,5 @@ public class DatabaseServiceImpl implements DatabaseService {
}
FileUtil.downloadExcel(list, response);
}
}
......@@ -13,20 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.impl;
package com.zq.admin.modules.mnt.service.impl;
import cn.hutool.core.util.IdUtil;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.system.modules.mnt.service.dto.DeployHistoryDto;
import com.zq.system.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import com.zq.system.modules.mnt.service.mapstruct.DeployHistoryMapper;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.repository.DeployHistoryRepository;
import com.zq.admin.modules.mnt.service.DeployHistoryService;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryDto;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryQueryCriteria;
import com.zq.admin.modules.mnt.service.mapstruct.DeployHistoryMapper;
import com.zq.admin.utils.FileUtil;
import com.zq.admin.utils.PageUtil;
import com.zq.admin.utils.QueryHelp;
import com.zq.admin.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import com.zq.system.modules.mnt.repository.DeployHistoryRepository;
import com.zq.system.modules.mnt.service.DeployHistoryService;
import com.zq.system.utils.FileUtil;
import com.zq.system.utils.PageUtil;
import com.zq.system.utils.QueryHelp;
import com.zq.system.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
......@@ -37,9 +37,9 @@ import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Service
@RequiredArgsConstructor
public class DeployHistoryServiceImpl implements DeployHistoryService {
......@@ -48,20 +48,20 @@ public class DeployHistoryServiceImpl implements DeployHistoryService {
private final DeployHistoryMapper deployhistoryMapper;
@Override
public Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable){
Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Object queryAll(DeployHistoryQueryCriteria criteria, Pageable pageable) {
Page<DeployHistory> page = deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(deployhistoryMapper::toDto));
}
@Override
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria){
return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<DeployHistoryDto> queryAll(DeployHistoryQueryCriteria criteria) {
return deployhistoryMapper.toDto(deployhistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
public DeployHistoryDto findById(String id) {
DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new);
ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id);
ValidationUtil.isNull(deployhistory.getId(), "DeployHistory", "id", id);
return deployhistoryMapper.toDto(deployhistory);
}
......@@ -94,4 +94,5 @@ public class DeployHistoryServiceImpl implements DeployHistoryService {
}
FileUtil.downloadExcel(list, response);
}
}
......@@ -13,20 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.impl;
package com.zq.admin.modules.mnt.service.impl;
import com.zq.admin.modules.mnt.domain.ServerDeploy;
import com.zq.admin.modules.mnt.repository.ServerDeployRepository;
import com.zq.admin.modules.mnt.service.ServerDeployService;
import com.zq.admin.modules.mnt.service.dto.ServerDeployDto;
import com.zq.admin.modules.mnt.service.dto.ServerDeployQueryCriteria;
import com.zq.admin.modules.mnt.service.mapstruct.ServerDeployMapper;
import com.zq.admin.modules.mnt.util.ExecuteShellUtil;
import com.zq.admin.utils.FileUtil;
import com.zq.admin.utils.PageUtil;
import com.zq.admin.utils.QueryHelp;
import com.zq.admin.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import com.zq.system.modules.mnt.domain.ServerDeploy;
import com.zq.system.modules.mnt.repository.ServerDeployRepository;
import com.zq.system.modules.mnt.service.ServerDeployService;
import com.zq.system.modules.mnt.service.dto.ServerDeployDto;
import com.zq.system.modules.mnt.service.dto.ServerDeployQueryCriteria;
import com.zq.system.modules.mnt.service.mapstruct.ServerDeployMapper;
import com.zq.system.modules.mnt.util.ExecuteShellUtil;
import com.zq.system.utils.FileUtil;
import com.zq.system.utils.PageUtil;
import com.zq.system.utils.QueryHelp;
import com.zq.system.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
......@@ -37,9 +37,9 @@ import java.io.IOException;
import java.util.*;
/**
* @author zhanghouying
* @date 2019-08-24
*/
* @author zhanghouying
* @date 2019-08-24
*/
@Service
@RequiredArgsConstructor
public class ServerDeployServiceImpl implements ServerDeployService {
......@@ -48,20 +48,20 @@ public class ServerDeployServiceImpl implements ServerDeployService {
private final ServerDeployMapper serverDeployMapper;
@Override
public Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable){
Page<ServerDeploy> page = serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Object queryAll(ServerDeployQueryCriteria criteria, Pageable pageable) {
Page<ServerDeploy> page = serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(serverDeployMapper::toDto));
}
@Override
public List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria){
return serverDeployMapper.toDto(serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria) {
return serverDeployMapper.toDto(serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
public ServerDeployDto findById(Long id) {
ServerDeploy server = serverDeployRepository.findById(id).orElseGet(ServerDeploy::new);
ValidationUtil.isNull(server.getId(),"ServerDeploy","id",id);
ValidationUtil.isNull(server.getId(), "ServerDeploy", "id", id);
return serverDeployMapper.toDto(server);
}
......@@ -71,33 +71,33 @@ public class ServerDeployServiceImpl implements ServerDeployService {
return serverDeployMapper.toDto(deploy);
}
@Override
public Boolean testConnect(ServerDeploy resources) {
ExecuteShellUtil executeShellUtil = null;
try {
executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort());
return executeShellUtil.execute("ls")==0;
} catch (Exception e) {
return false;
}finally {
if (executeShellUtil != null) {
executeShellUtil.close();
}
}
}
@Override
public Boolean testConnect(ServerDeploy resources) {
ExecuteShellUtil executeShellUtil = null;
try {
executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(), resources.getPort());
return executeShellUtil.execute("ls") == 0;
} catch (Exception e) {
return false;
} finally {
if (executeShellUtil != null) {
executeShellUtil.close();
}
}
}
@Override
@Override
@Transactional(rollbackFor = Exception.class)
public void create(ServerDeploy resources) {
serverDeployRepository.save(resources);
serverDeployRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(ServerDeploy resources) {
ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new);
ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId());
serverDeploy.copy(resources);
ValidationUtil.isNull(serverDeploy.getId(), "ServerDeploy", "id", resources.getId());
serverDeploy.copy(resources);
serverDeployRepository.save(serverDeploy);
}
......@@ -123,4 +123,5 @@ public class ServerDeployServiceImpl implements ServerDeployService {
}
FileUtil.downloadExcel(list, response);
}
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.mapstruct;
package com.zq.admin.modules.mnt.service.mapstruct;
import com.zq.system.base.BaseMapper;
import com.zq.system.modules.mnt.domain.App;
import com.zq.system.modules.mnt.service.dto.AppDto;
import com.zq.admin.base.BaseMapper;
import com.zq.admin.modules.mnt.domain.App;
import com.zq.admin.modules.mnt.service.dto.AppDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface AppMapper extends BaseMapper<AppDto, App> {
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.mapstruct;
package com.zq.admin.modules.mnt.service.mapstruct;
import com.zq.system.base.BaseMapper;
import com.zq.system.modules.mnt.domain.Database;
import com.zq.system.modules.mnt.service.dto.DatabaseDto;
import com.zq.admin.base.BaseMapper;
import com.zq.admin.modules.mnt.domain.Database;
import com.zq.admin.modules.mnt.service.dto.DatabaseDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DatabaseMapper extends BaseMapper<DatabaseDto, Database> {
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.mapstruct;
package com.zq.admin.modules.mnt.service.mapstruct;
import com.zq.system.base.BaseMapper;
import com.zq.system.modules.mnt.domain.DeployHistory;
import com.zq.system.modules.mnt.service.dto.DeployHistoryDto;
import com.zq.admin.base.BaseMapper;
import com.zq.admin.modules.mnt.domain.DeployHistory;
import com.zq.admin.modules.mnt.service.dto.DeployHistoryDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DeployHistoryMapper extends BaseMapper<DeployHistoryDto, DeployHistory> {
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.mapstruct;
package com.zq.admin.modules.mnt.service.mapstruct;
import com.zq.system.base.BaseMapper;
import com.zq.system.modules.mnt.domain.Deploy;
import com.zq.system.modules.mnt.service.dto.DeployDto;
import com.zq.admin.base.BaseMapper;
import com.zq.admin.modules.mnt.domain.Deploy;
import com.zq.admin.modules.mnt.service.dto.DeployDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {AppMapper.class, ServerDeployMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring", uses = {AppMapper.class, ServerDeployMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DeployMapper extends BaseMapper<DeployDto, Deploy> {
}
......@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.service.mapstruct;
package com.zq.admin.modules.mnt.service.mapstruct;
import com.zq.system.base.BaseMapper;
import com.zq.system.modules.mnt.domain.ServerDeploy;
import com.zq.system.modules.mnt.service.dto.ServerDeployDto;
import com.zq.admin.base.BaseMapper;
import com.zq.admin.modules.mnt.domain.ServerDeploy;
import com.zq.admin.modules.mnt.service.dto.ServerDeployDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
* @author zhanghouying
* @date 2019-08-24
*/
@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ServerDeployMapper extends BaseMapper<ServerDeployDto, ServerDeploy> {
}
......@@ -17,59 +17,90 @@
*
*/
package com.zq.system.modules.mnt.util;
package com.zq.admin.modules.mnt.util;
import lombok.extern.slf4j.Slf4j;
/**
* @author /
*/
@Slf4j
@SuppressWarnings({"unchecked","all"})
@SuppressWarnings({"unchecked", "all"})
public enum DataTypeEnum {
/** mysql */
/**
* mysql
*/
MYSQL("mysql", "mysql", "com.mysql.jdbc.Driver", "`", "`", "'", "'"),
/** oracle */
/**
* oracle
*/
ORACLE("oracle", "oracle", "oracle.jdbc.driver.OracleDriver", "\"", "\"", "\"", "\""),
/** sql server */
/**
* sql server
*/
SQLSERVER("sqlserver", "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "\"", "\"", "\"", "\""),
/** h2 */
/**
* h2
*/
H2("h2", "h2", "org.h2.Driver", "`", "`", "\"", "\""),
/** phoenix */
/**
* phoenix
*/
PHOENIX("phoenix", "hbase phoenix", "org.apache.phoenix.jdbc.PhoenixDriver", "", "", "\"", "\""),
/** mongo */
/**
* mongo
*/
MONGODB("mongo", "mongodb", "mongodb.jdbc.MongoDriver", "`", "`", "\"", "\""),
/** sql4es */
/**
* sql4es
*/
ELASTICSEARCH("sql4es", "elasticsearch", "nl.anchormen.sql4es.jdbc.ESDriver", "", "", "'", "'"),
/** presto */
/**
* presto
*/
PRESTO("presto", "presto", "com.facebook.presto.jdbc.PrestoDriver", "", "", "\"", "\""),
/** moonbox */
/**
* moonbox
*/
MOONBOX("moonbox", "moonbox", "moonbox.jdbc.MbDriver", "`", "`", "`", "`"),
/** cassandra */
/**
* cassandra
*/
CASSANDRA("cassandra", "cassandra", "com.github.adejanovski.cassandra.jdbc.CassandraDriver", "", "", "'", "'"),
/** click house */
/**
* click house
*/
CLICKHOUSE("clickhouse", "clickhouse", "ru.yandex.clickhouse.ClickHouseDriver", "", "", "\"", "\""),
/** kylin */
/**
* kylin
*/
KYLIN("kylin", "kylin", "org.apache.kylin.jdbc.Driver", "\"", "\"", "\"", "\""),
/** vertica */
/**
* vertica
*/
VERTICA("vertica", "vertica", "com.vertica.jdbc.Driver", "", "", "'", "'"),
/** sap */
/**
* sap
*/
HANA("sap", "sap hana", "com.sap.db.jdbc.Driver", "", "", "'", "'"),
/** impala */
/**
* impala
*/
IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'");
private String feature;
......
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.util;
package com.zq.admin.modules.mnt.util;
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
......@@ -35,69 +35,69 @@ import java.util.Vector;
@Slf4j
public class ExecuteShellUtil {
private Vector<String> stdout;
private Vector<String> stdout;
Session session;
Session session;
public ExecuteShellUtil(final String ipAddress, final String username, final String password, int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
public ExecuteShellUtil(final String ipAddress, final String username, final String password, int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return -1;
} finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public void close(){
if (session != null) {
session.disconnect();
}
}
public void close() {
if (session != null) {
session.disconnect();
}
}
public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zq.system.modules.mnt.util;
package com.zq.admin.modules.mnt.util;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
......@@ -26,80 +26,81 @@ import java.util.logging.Logger;
/**
* 远程执行linux命令
*
* @author: ZhangHouYing
* @date: 2019-08-10 10:06
*/
public class ScpClientUtil {
static private Map<String,ScpClientUtil> instance = Maps.newHashMap();
static private Map<String, ScpClientUtil> instance = Maps.newHashMap();
static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String password) {
if (instance.get(ip) == null) {
instance.put(ip, new ScpClientUtil(ip, port, username, password));
}
return instance.get(ip);
}
static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String password) {
if (instance.get(ip) == null) {
instance.put(ip, new ScpClientUtil(ip, port, username, password));
}
return instance.get(ip);
}
public ScpClientUtil(String ip, int port, String username, String password) {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public ScpClientUtil(String ip, int port, String username, String password) {
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public void getFile(String remoteFile, String localTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localTargetDirectory);
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
}finally{
conn.close();
}
}
public void getFile(String remoteFile, String localTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localTargetDirectory);
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
} finally {
conn.close();
}
}
public void putFile(String localFile, String remoteTargetDirectory) {
putFile(localFile, null, remoteTargetDirectory);
}
public void putFile(String localFile, String remoteTargetDirectory) {
putFile(localFile, null, remoteTargetDirectory);
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
putFile(localFile, remoteFileName, remoteTargetDirectory,null);
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
putFile(localFile, remoteFileName, remoteTargetDirectory, null);
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
if ((mode == null) || (mode.length() == 0)) {
mode = "0600";
}
if (remoteFileName == null) {
client.put(localFile, remoteTargetDirectory);
} else {
client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
}
} catch (IOException ex) {
Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex);
}finally{
conn.close();
}
}
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
if ((mode == null) || (mode.length() == 0)) {
mode = "0600";
}
if (remoteFileName == null) {
client.put(localFile, remoteTargetDirectory);
} else {
client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
}
} catch (IOException ex) {
Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex);
} finally {
conn.close();
}
}
private String ip;
private int port;
private String username;
private String password;
private String ip;
private int port;
private String username;
private String password;
}
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