init: plm service

This commit is contained in:
wht
2025-03-31 12:03:06 +08:00
commit 62682dcb5b
353 changed files with 30871 additions and 0 deletions

31
.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/

31
commons/.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
commons/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

286
commons/pom.xml Normal file
View File

@ -0,0 +1,286 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.centricsoftware</groupId>
<artifactId>plmservice</artifactId>
<version>2.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>commons</artifactId>
<version>2.1</version>
<packaging>jar</packaging>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<st4.version>4.1</st4.version>
<elasticsearch.version>7.0.1</elasticsearch.version>
<jxl.version>2.6.12</jxl.version>
<jxl.core.version>1.0.3</jxl.core.version>
<!--<poi.version>3.17</poi.version>-->
<!--使用用hutool excel方法需要poi版本大于4.1.2-->
<poi.version>4.1.2</poi.version>
<commons-net.version>3.6</commons-net.version>
<mail.version>1.4.7</mail.version>
<jug.version>2.0.0</jug.version>
<jcifs.version>1.3.17</jcifs.version>
<bcprov-jdk15on.version>1.56</bcprov-jdk15on.version>
<velocity-engine-core.version>2.0</velocity-engine-core.version>
<jsr311-api.version>1.1.1</jsr311-api.version>
<itextpdf.version>5.5.13</itextpdf.version>
<itext-asian.version>5.2.0</itext-asian.version>
<aspose-cells.version>8.5.2</aspose-cells.version>
<zxing.core.version>3.4.0</zxing.core.version>
<jettson.version>1.3.8</jettson.version>
<easyexcel.version>3.3.3</easyexcel.version>
<json-path.version>2.4.0</json-path.version>
</properties>
<dependencies>
<!--hse start-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--hse end-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
<!-- <optional>true</optional>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bcprov-jdk15on.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity-engine-core.version}</version>
</dependency>
<!-- native export依赖 -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>${jsr311-api.version}</version>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>config</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 字符串模板 -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>ST4</artifactId>
<version>${st4.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>cn.hutool</groupId>-->
<!-- <artifactId>hutool-all</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
</dependency>
<!--Excel工具类相关依赖 jxl poi-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>${jxl.version}</version>
</dependency>
<!--Excel工具类相关依赖 jxl poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!--Excel工具类相关依赖 jxl poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--Excel工具类相关依赖 jxl poi-->
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>${jxl.core.version}</version>
</dependency>
<!-- FtpUtil相关依赖 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<!-- json相关spring推荐使用jackson这里不在推荐使用fastjson目前阿里巴巴对fastjson类库的bug修复速度并不尽如人意而且
经常爆发出内存溢出bug-->
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>${jettson.version}</version>
</dependency>
<!--MailUtil 相关依赖 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
<!--SMBFileUtil 相关依赖-->
<dependency>
<groupId>jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>${jcifs.version}</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- pdf 依赖 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>${itextpdf.version}</version>
</dependency>
<!-- pdf 依赖 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>${itext-asian.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${json-path.version}</version>
</dependency>
<!-- excel转pdf -->
<!-- <dependency>-->
<!-- <groupId>com.aspose</groupId>-->
<!-- <artifactId>aspose-cells</artifactId>-->
<!-- <version>${aspose-cells.version}</version>-->
<!-- </dependency>-->
<!-- sqlserver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<!-- 谷歌二维码依赖 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>${zxing.core.version}</version>
</dependency>
<!-- feign相关 开始-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>10.1.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>10.1.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId> feign-form-spring</artifactId>
<version>3.8.0</version>
</dependency>
<!-- feign相关 结束-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
</repositories>
<build>
<finalName>plmservice-commons</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>license.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,40 @@
package com.centricsoftware.commons.ant;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* 自定义注解拦截Controller
* @author ZhengGong
* @date 2019/6/25
*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerLog {
String value() default "";
/**
* 是否记录响应信息
* @author liaochangjiang
* @since 2024-05-07 17:11
*/
boolean response() default false;
/**
* 是否接口日志
*/
boolean interfaceLog() default false;
/**
* 请求报文中key的字段支持getByPath
*/
String requestId() default "";
/**
* 响应报文中成功的字段支持getByPath
*/
String responseId() default "";
}

View File

@ -0,0 +1,15 @@
package com.centricsoftware.commons.ant;
import java.lang.annotation.*;
/**
* 自定义注解拦截service
* @author ZhengGong
* @date 2019/6/25
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ServiceLog {
String value() default "";
}

View File

@ -0,0 +1,13 @@
package com.centricsoftware.commons.dto;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@ToString(callSuper = true)
@Accessors(chain = true)
public class PlmPageReqVo<T> {
private Long pageNum = 1L;
private Long pageSize = 10L;
}

View File

@ -0,0 +1,35 @@
package com.centricsoftware.commons.dto;
import com.centricsoftware.commons.em.ResCode;
import com.centricsoftware.commons.exception.BaseException;
/**
* @Description: PLM工具类异常基类
* @Author: ZhengGong
* @CreateDate: 2019/5/20 15:11
* @Company: Centric
*/
public class PlmUtilsException extends BaseException {
public PlmUtilsException(ResCode code) {
super(code);
}
public PlmUtilsException(ResCode code, Object data) {
super(code,data);
}
public PlmUtilsException(Integer code, String message) {
super(code,message);
}
public PlmUtilsException(Integer code, String message, Object data) {
super(code,message,data);
}
public PlmUtilsException(ResCode code, Throwable e){
super(code);
}
}

View File

@ -0,0 +1,37 @@
package com.centricsoftware.commons.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 返回信息实体类
* @author ZhengGong
* @date 2020/4/16
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ResEntity implements Serializable {
/**
* 错误编号
*/
private Integer code;
/**
* 错误信息
*/
private String msg;
/**
* 返回对象
*/
private Object data;
/**
* 是否成功
*/
private boolean success;
}

View File

@ -0,0 +1,132 @@
package com.centricsoftware.commons.dto;
import cn.hutool.core.util.StrUtil;
import com.centricsoftware.commons.em.ResCode;
import com.centricsoftware.commons.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.stringtemplate.v4.ST;
import java.net.URLEncoder;
/**
* 接口返回信息
* @author ZhengGong
* @date 2019/9/16
*/
@Slf4j
public class WebResponse {
/**
* 失败返回特定的消息实体
* @param code 错误代码
* @param message 错误信息
* @param data 具体消息实体
* @return 消息实体ResEntity
*/
public static ResEntity failure(Integer code, String message, Object data) {
return ResEntity.builder().code(code).msg(message).data(data).success(false).build();
}
/**
* 失败返回特定的消息实体
* @param code 错误代码
* @param message 错误信息
* @return 消息实体ResEntity
*/
public static ResEntity failure(Integer code, String message) {
return ResEntity.builder().code(code).msg(message).success(false).build();
}
/**
* 失败返回特定的消息实体
* @param respCode 错误代码封装枚举类
* @param data 具体消息实体
* @return 消息实体ResEntity
*/
public static ResEntity failure(ResCode respCode, Object data) {
return getStringObjectMap(respCode, data,false);
}
/**
* 失败返回特定的消息实体
* @param respCode 错误代码封装枚举类
* @return 消息实体ResEntity
*/
public static ResEntity failure(ResCode respCode) {
return getStringObjectMap(respCode,false);
}
/**
* 失败返回特定的消息实体
* @param e 错误基类
* @return 消息实体ResEntity
*/
public static<T extends BaseException> ResEntity failure(T e){
return failure(e.getCode(),e.getMessage(),e.getData());
}
/**
* 错误302到具体的页面
* @param stp 模板链接
* @param msg 错误信息
* @return 页面链接
*/
public static String failurePage(String stp,String msg) {
try {
ST st=new ST(stp);
st.add("ERROR", URLEncoder.encode(msg,"UTF-8"));
return "redirect:"+st.render();
} catch (Exception e) {
log.error("error:",e);
return null;
}
}
/**
* 成功返回特定的状态码和信息
* @param respCode 成功代码封装枚举类
* @param data 具体消息实体
* @return 消息实体ResEntity
*/
public static ResEntity success(ResCode respCode, Object data) {
return getStringObjectMap(respCode, data,true);
}
private static ResEntity getStringObjectMap(ResCode respCode, Object data, Boolean success) {
return ResEntity.builder().code( respCode.getCode()).msg( respCode.getMessage()).data(data).success(success).build();
}
/**
* 成功返回特定的状态码和信息
* @param respCode 成功代码封装枚举类
* @return 消息实体ResEntity
*/
public static ResEntity success(ResCode respCode) {
return getStringObjectMap(respCode,true);
}
private static ResEntity getStringObjectMap(ResCode respCode, Boolean success) {
return ResEntity.builder().code(respCode.getCode()).msg(respCode.getMessage()).success(success).build();
}
public static ResEntity failure(String message){
return ResEntity.builder().code(ResCode.ERROR.getCode()).msg(message).success(false).build();
}
public static ResEntity success(String message){
return ResEntity.builder().code(ResCode.SUCCESS.getCode()).msg(message).success(true).build();
}
public static ResEntity autoResponse(Object obj,String error) {
if(StrUtil.isBlank(error)){
return ResEntity.builder().code(ResCode.SUCCESS.getCode()).msg(ResCode.SUCCESS.getMessage()).success(true).data(obj).build();
}else{
return ResEntity.builder().code(ResCode.ERROR.getCode()).msg(error).success(false).data(obj).build();
}
}
}

View File

@ -0,0 +1,31 @@
package com.centricsoftware.commons.dto.enum4cache;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;
@Slf4j
@Data
public class EnumList {
private String dependsOn;
private String description;
private List<String> enums;
private String nodeName;
private List<String> values;
private List<EnumValue> enumValues;
private Map<String,String> descCache;//描述fullname fullname描述
private Map<String,String> displayEnCache;//翻译值fullname
private Map<String,String> displayZhCache;//翻译值fullname
}

View File

@ -0,0 +1,20 @@
package com.centricsoftware.commons.dto.enum4cache;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class EnumValue {
private boolean active;
private String dependsOn;
private String description;
private String nodeName;
private String value;
}

View File

@ -0,0 +1,14 @@
package com.centricsoftware.commons.em;
public enum C8ImportTypeEnum {
REF,
STRING,
BOOLEAN,
ENUM,
ENUM_DESC,
ENUM_DISPLAY,
TIME,
INTEGER,
DOUBLE,
REFLIST
}

View File

@ -0,0 +1,5 @@
package com.centricsoftware.commons.em;
public enum C8NativeExportType {
STRING, DOUBLE, INTEGER, BOOLEAN, URL, URL_ID, ENUM, ENUM_KEY, ENUM_DESC, ENUM_DISPLAY, TIME, LONG
}

View File

@ -0,0 +1,67 @@
package com.centricsoftware.commons.em;
import lombok.Getter;
/**
* 错误码枚举类
*
* @author ZhengGong
* @date 2019/6/12
*/
@Getter
public enum ResCode {
SUCCESS(0, "成功!"),
OK(200, "OK"),
ERROR(201, "失败"),
REQUEST_NOT_FOUND(202, "请求不存在!"),
HTTP_BAD_METHOD(203, "请求方式不支持!"),
BAD_REQUEST(204, "请求异常!"),
PARAM_NOT_MATCH(205, "参数不匹配!"),
PARAM_NOT_NULL(206, "参数不能为空!"),
JSON_PARSE_ERROR(207, "JSON转换异常"),
C8_UNSUPPORTED_ENCODING_ERROR(208, "双编码异常"),
AUTHORIZE_ERROR(209, "请求未授权!"),
AUTHORIZE_UP_ERROR(210, "请求未授权,账号或密码错误!"),
CONFIG_NOT_INIT(666, "配置未初始化!"),
/**
* 业务类
*/
DMP_DATA_NULL(3001, "找不到对应的数据,或者数据已经同步成功"),
DMP_DATA_TRANSLATE_FAIL(3002, "调用DMP同步数据失败请重试"),
DMP_FILE_URL_ILLEGAL(3003, "获取到的DMP文件路径不合法"),
DMP_FILE_PUBLISH_ERROR(3004, "DMP发布文件失败"),
SKU_CODE_NOTFOUND(3005, "SKU CODE没有找到相关的SKU数据"),
SKU_CODE_DUPLICATE(3006, "SKU CODE找出重复的数据,请联系管理员"),
SKU_CODE_EMPTY(3007, "SKU CODE为空"),
RECORD_LOCK(888, "数据正在执行更新,已被锁定,请稍后再试"),
SYSTEM_RUNTIME_ERROR(999, "系统异常!");
private Integer code;
private String message;
ResCode(Integer code, String message) {
this.code = code;
this.message = message;
}
/**
* 通过code返回枚举
*
* @param code
* @return
*/
public static ResCode parse(Integer code) {
ResCode[] values = values();
for (ResCode value : values) {
if (value.getCode().equals(code)) {
return value;
}
}
throw new RuntimeException("Unknown code of ResultEnum");
}
}

View File

@ -0,0 +1,52 @@
package com.centricsoftware.commons.exception;
import com.centricsoftware.commons.em.ResCode;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 异常基类
* @author ZhengGong
* @date 2019/6/18
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class BaseException extends RuntimeException {
private Integer code;
private String message;
private Object data;
public BaseException(ResCode resCode) {
super(resCode.getMessage());
this.code = resCode.getCode();
this.message = resCode.getMessage();
}
public BaseException(ResCode resCode, Object data) {
this(resCode);
this.data = data;
}
public BaseException(Integer code, String message) {
super(message);
this.code = code;
this.message = message;
}
public BaseException(Integer code, String message, Object data) {
this(code, message);
this.data = data;
}
public BaseException(ResCode code, Throwable e){
this(code);
data = e;
}
public ResCode getResCode(){
return ResCode.parse(code);
}
}

View File

@ -0,0 +1,30 @@
package com.centricsoftware.commons.exception;
import com.centricsoftware.commons.em.ResCode;
/**
* c8 uri双编码异常
* @author zheng.gong
* @date 2020/5/12
*/
public class C8UnsupportedEncodingException extends BaseException {
public C8UnsupportedEncodingException(ResCode code) {
super(code);
}
public C8UnsupportedEncodingException(ResCode code, Object data) {
super(code,data);
}
public C8UnsupportedEncodingException(Integer code, String message) {
super(code,message);
}
public C8UnsupportedEncodingException(Integer code, String message, Object data) {
super(code,message,data);
}
public C8UnsupportedEncodingException(ResCode code, Throwable e){
super(code);
}
}

View File

@ -0,0 +1,30 @@
package com.centricsoftware.commons.exception;
import com.centricsoftware.commons.em.ResCode;
/**
* 参数异常
* @author ZhengGong
* @date 2019/9/16
*/
public class ParamException extends BaseException {
public ParamException(ResCode code) {
super(code);
}
public ParamException(ResCode code, Object data) {
super(code,data);
}
public ParamException(Integer code, String message) {
super(code,message);
}
public ParamException(Integer code, String message, Object data) {
super(code,message,data);
}
public ParamException(ResCode code, Throwable e){
super(code);
}
}

View File

@ -0,0 +1,31 @@
package com.centricsoftware.commons.exception;
import com.centricsoftware.commons.em.ResCode;
import com.centricsoftware.commons.exception.BaseException;
/**
* 请求参数异常
* @author ZhengGong
* @date 2019/9/16
*/
public class RequestArgsException extends BaseException {
public RequestArgsException(ResCode resCode) {
super(resCode);
}
public RequestArgsException(ResCode resCode, Object data) {
super(resCode, data);
}
public RequestArgsException(Integer code, String message) {
super(code, message);
}
public RequestArgsException(Integer code, String message, Object data) {
super(code, message, data);
}
public RequestArgsException(ResCode code, Throwable e) {
super(code, e);
}
}

View File

@ -0,0 +1,91 @@
package com.centricsoftware.commons.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* csv处理工具类
* 同类方法 {@link cn.hutool.core.text.csv.CsvUtil}
* @author zheng.gong
* @date 2020/4/27
*/
public class CSVParser {
public List<String[]> parse(File file) throws Exception {
List<String[]> result = new ArrayList<String[]>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
try {
String line = null;
while ((line = in.readLine()) != null) {
result.add(parseLine(line));
}
} finally {
if (in != null) {
in.close();
}
}
return result;
}
enum State {
Normal, QuoteBegin, Quote, QuoteEnd,
}
public String[] parseLine(String line) {
ArrayList<String> list = new ArrayList<String>();
State state = State.Normal;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < line.length(); ++i) {
char ch = line.charAt(i);
switch (state) {
case Normal:
if (ch == ',') {
list.add(sb.toString());
sb.setLength(0);
} else if (ch == '"') {
state = State.QuoteBegin;
} else {
sb.append(ch);
}
break;
case QuoteBegin:
if (ch == '"') {
state = State.Normal;
sb.append('"');
} else {
state = State.Quote;
sb.append(ch);
}
break;
case Quote:
if (ch == '"') {
state = State.QuoteEnd;
} else {
sb.append(ch);
}
break;
case QuoteEnd:
if (ch == ',') {
state = State.Normal;
list.add(sb.toString());
sb.setLength(0);
} else if (ch == '"') {
state = State.Quote;
sb.append('"');
} else {
state = State.Normal;
sb.append(ch);
}
break;
}
}
list.add(sb.toString());
return list.toArray(new String[list.size()]);
}
}

View File

@ -0,0 +1,602 @@
package com.centricsoftware.commons.utils;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
@Slf4j
public class CommonUtil {
public static final String DAY_FORMAT = "yyyy-MM-dd";
public static final String DAY_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String YMD = "yyyyMMdd";
public static final String YYMD = "yyMMdd";
public static final String YYMD_HMS = "yyMMddHHmmss";
public static final String YMD_DASH = "yyyy-MM-dd";
public static final String YMD_SLASH = "yyyy/MM/dd";
public static final String YMD_HMS = "yyyyMMddHHmmss";
public static final String YMD_HMSS = "yyyyMMddHHmmssSSS";
public static final String YMD_HMS_DASH = "yyyy-MM-dd HH:mm:ss";
public static final String HMS_DASH = "HH:mm:ss";
/**
* 转换timestamp
*
* @param attrvalue
* @param attrformat
* @param CLASSNAME
* @return
* @author GHUANG
* @version 2019年6月10日 上午11:56:16
*/
public static String parseTimestamp(String attrvalue, String attrformat, String CLASSNAME) {
DateFormat format = new SimpleDateFormat(attrformat);
String svalue = "";
try {
Timestamp ts = new Timestamp(format.parse(attrvalue).getTime());
long tsvalue = ts.getTime() / 1000;
svalue = String.valueOf(tsvalue);
} catch (Exception e) {
log.error(CLASSNAME, e);
}
return svalue;
}
public static String getCurrentDate(String format) {
SimpleDateFormat sm = new SimpleDateFormat(format);
return sm.format(new Date());
}
public static String createTimeNo() {
SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyyMMdd");
fullDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT+8:00"));
String currentTime = fullDateFormat.format(new Date(System.currentTimeMillis()));
return currentTime;
}
public static String createTime() {
Timestamp d = new Timestamp(System.currentTimeMillis());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 定义格式
return df.format(d);
}
public static String createCurrentTimestamp(String CLASSNAME) {
String svalue = "";
try {
Timestamp d = new Timestamp(System.currentTimeMillis());
long tsvalue = d.getTime() / 1000;
svalue = String.valueOf(tsvalue);
} catch (Exception e) {
log.error(CLASSNAME, e);
}
return svalue;
}
public static HashMap changeStr2Map(String mapStr) {
HashMap<String, String> map = new HashMap<String, String>();
String cms = mapStr.replace("{", "").replace("}", "");
String[] mapStrs = cms.split(",");
for (String s : mapStrs) {
String[] ms = s.split("=");
System.out.println(s);
if (ms.length == 2) {
map.put(ms[0], ms[1]);
}
}
return map;
}
public static String escapeUrl(String value) {
if (value == null) {
return "";
}
String s = value.replaceAll("&", "&amp;");
s = s.replaceAll("<", "&lt;");
s = s.replaceAll(">", "&gt;");
s = s.replaceAll("\"", "&quot;");
s = s.replaceAll("'", "&apos;");
return s;
}
/**
* 拆分List
*
* @param list
* @param len
* @return
* @author GHUANG
* @version 2019年11月5日 下午3:35:49
*/
public static List splitList(List list, int len) {
List result = new ArrayList();
log.info("input list={},core={}",list,len);
if (list == null || list.size() == 0 || len < 1) {
result.add(list);
} else {
int size = list.size();
int count = (size + len - 1) / len;
for (int i = 0; i < count; i++) {
List subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
result.add(subList);
}
}
return result;
}
/**
* 拆分List
*
* @param map
* @param len
* @return
* @author GHUANG
* @version 2019年11月5日 下午3:35:49
*/
public static List splitMap(LinkedHashMap<String, ArrayList<String>> map, int len) {
List result = new ArrayList();
if (map == null || map.size() == 0 || len < 1) {
result.add(map);
} else {
int size = map.size();
int count = (size + len - 1) / len;
for (int i = 0; i < count; i++) {
int fromIndex = i * len;
int toIndex = ((i + 1) * len > size ? size : len * (i + 1));
LinkedHashMap<String, ArrayList<String>> newmap = new LinkedHashMap<String, ArrayList<String>>();
int j = 0;
for (Entry<String, ArrayList<String>> entry : map.entrySet()) {
if (j >= fromIndex && j < toIndex) {
newmap.put(entry.getKey(), entry.getValue());
}
j++;
}
result.add(newmap);
}
}
return result;
}
public static String escapeSpecUrl(String value) {
if (value == null) {
return "";
}
String s = value.replaceAll("&", "&amp;");
s = s.replaceAll("\"", "&quot;");
s = s.replaceAll("'", "&apos;");
// s = stripBadChar(s);
return s;
}
public static String getExtractXML(ArrayList<HashMap<String, String>> list, String spec) {
String extractXML = "";
extractXML += "<EXTRACT>\n";
for (int i = 0; i < list.size(); i++) {
HashMap<String, String> map = list.get(i);
String path = map.get("path");
if (path.length() > 0) {
path = " Path=\"" + path + "\"";
} else {
path = "";
}
extractXML += " <DETAIL AttributeName=\"" + map.get("name") + "\" " + path + " Seq=\""
+ (i + 1) + "\"/>\n";
}
if (extractXML.length() > 0) {
extractXML += spec;
}
extractXML += "</EXTRACT>\n";
return extractXML;
}
public static String getQueryXML(String nodetype, ArrayList<HashMap<String, String>> list, String notcondition,
String order) {
// TODO Auto-generated method stub
String queryXML = "";
queryXML += "<QUERY>\n";
queryXML += " <AND>\n";
queryXML += " <Predicate NodeType=\"" + nodetype + "\" Operand=\"EQ\"/>\n";
if (notcondition.length() > 0) {
queryXML += notcondition;
}
queryXML += " <OR>\n";
for (HashMap<String, String> map : list) {
String path = map.get("path");
String attrkey = map.get("key");
String attrvalue = map.get("value");
String attrtype = map.get("type");
if (attrtype.equalsIgnoreCase("string")) {
queryXML += " <Predicate Path=\"" + path + "\" AttributeName=\"" + attrkey
+ "\" Operand=\"EQ\" ValueString=\""
+ attrvalue
+ "\" />\n";
} else if (attrtype.equalsIgnoreCase("ref")) {
queryXML += " <Predicate Path=\"" + path + "\" AttributeName=\"" + attrkey
+ "\" Operand=\"EQ\" ValueRef=\""
+ attrvalue
+ "\" />\n";
} else if (attrtype.equalsIgnoreCase("double")) {
queryXML += " <Predicate Path=\"" + path + "\" AttributeName=\"" + attrkey
+ "\" Operand=\"EQ\" ValueNumber=\""
+ attrvalue
+ "\" />\n";
}
}
queryXML += " </OR>\n";
queryXML += " </AND>\n";
queryXML += order;
queryXML += "</QUERY>\n";
return queryXML;
}
public static Locale getLocaleFromLocaleName(String localeName) {
Locale locale = null;
if (!StringUtils.isEmpty(localeName)) {
locale = Locale.forLanguageTag(localeName.replace('_', '-'));
}
return locale;
}
public static String stripBadChar(String s) {
StringBuilder out = new StringBuilder(s.length() * 6);
byte[] bytes = s.getBytes();
for (int j = 0; j < bytes.length; ++j) {
byte b = bytes[j];
int i = b;
if (i < 0) {
i = 256 + i;
}
if (i > '~') {
String cc = "&#" + i + ";";
out.append(cc);
} else {
char current = (char) b;
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF))) {
out.append(current);
}
}
}
s = out.toString();
return s;
}
public static String writeFileToDisk(byte[] img, String filePath, String fileName) {
String path = "";
try {
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
path = filePath + fileName;
File file = new File(path);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
/**
*
* @param json
* @param classname
* @param LOG
* @return
* @author GHUANG
* @version 2019年6月10日 下午1:08:45
*/
// public static HashMap parseXML(String type, JSONObject json, String classname) throws Exception{
//
// String keys = CSProperties.getValue("cs." + type + ".import.keys", "");
//
// List<String> keylist = Arrays.asList(keys.split(","));
// HashMap objmap = new HashMap();
// try {
// for (String key : keylist) {
// String xml = "";
// String attrname = CSProperties.getValue("cs." + type + ".import." + key + ".attrname", "");
// String attrtype = CSProperties.getValue("cs." + type + ".import." + key + ".attrtype", "");
// String refobj = CSProperties.getValue("cs." + type + ".import." + key + ".refobject", "");
// String refkey = CSProperties.getValue("cs." + type + ".import." + key + ".refkey", "");
// String refpath = CSProperties.getValue("cs." + type + ".import." + key + ".refpath", "");
// String attrpath = CSProperties.getValue("cs." + type + ".import." + key + ".attrpath", "");
// if (json.isNull(key)) {
// continue;
// }
// if (json.has(key)) {
// String attrvalue = json.getString(key);
// if (attrtype.equals("enumKEY")) {
// xml += "<ChangeAttribute Id=\"" + attrname + "\" Type=\"enum\" Value=\""
// + refobj + attrvalue + "\" />";
// ;
// } else if (attrtype.equals("enumNAME")) {
// for (Entry<String, String> gmap : NodeUtil.zhLocaleMap.entrySet()) {
// if (gmap.getValue().equals(attrvalue) && gmap.getKey().contains(refobj)) {
// xml += "<ChangeAttribute Id=\"" + attrname + "\" Type=\"enum\" Value=\""
// + gmap.getKey() + "\" />";
//
// }
// }
// } else if (attrtype.equals("time")) {
// String timestr = CommonUtil.parseTimestamp(attrvalue, refobj, classname);
// xml += "<ChangeAttribute Id=\"" + attrname + "\" Type=\"" + attrtype + "\" Value=\""
// + timestr + "\" />";
// } else if (attrtype.equals("integer")) {
// xml += "<ChangeAttribute Type=\"" + attrtype + "\" Id=\"" + attrname + "\" Value=\""
// + Integer.valueOf(attrvalue)
// + "\" />";
// } else if (attrtype.equals("ref")) {
// String queryxml = "<Node Parameter=\"Type\" Op=\"EQ\" Value=\"" + refobj + "\" />\r\n" +
// "<Attribute Path=\"" + refpath + "\" Id=\"" + refkey + "\" Op=\"EQ\" SValue=\""
// + attrvalue + "\" />";
// List refobjlist = NodeUtil.queryBOByXML(queryxml);
// if (refobjlist.size() > 0) {
// xml += "<ChangeAttribute Id=\"" + attrname + "\" Type=\"" + attrtype + "\" Value=\""
// + refobjlist.get(0) + "\" />";
//
// }
// } else if (attrtype.equals("reflist")) {
// List<String> valuelist = Arrays.asList(attrvalue);
// if (valuelist.size() > 0) {
// xml += "<ChangeAttribute Id=\"" + attrname + "\" Type=\"" + attrtype + "\" />";
// for (String value : valuelist) {
// String queryxml = "<Node Parameter=\"Type\" Op=\"EQ\" Value=\"" + refobj + "\" />\r\n" +
// "<Attribute Path=\"" + refpath + "\" Id=\"" + value + "\" Op=\"EQ\" SValue=\""
// + attrvalue + "\" />";
// List refobjlist = NodeUtil.queryBOByXML(queryxml);
// xml += "<ref>" + refobjlist.get(0) + "</ref>";
// }
// xml += "</ChangeAttribute>";
// }
// } else {
// xml += " <ChangeAttribute Id=\"" + attrname + "\" Type=\"" + attrtype
// + "\" ><![CDATA[" + attrvalue + "]]></ChangeAttribute>";
//
// }
// }
// if (attrpath == null || attrpath.length() == 0) {
// if (objmap.containsKey("default")) {
// String tempxml = (String) objmap.get("default");
// objmap.put("default", xml + tempxml);
// } else {
// objmap.put("default", xml);
// }
// } else {
// System.out.println("---" + attrpath);
// if (objmap.containsKey(attrpath)) {
// String tempxml = (String) objmap.get(attrpath);
// objmap.put(attrpath, xml + tempxml);
// } else {
// objmap.put(attrpath, xml);
// }
// }
// }
// } catch (Exception e) {
// log.info(classname, e);
// }
// return objmap;
// }
/**
* 四舍五入
*
* @param attrvalue
* @param dot
* @return
* @author GHUANG
* @version 2019年6月18日 下午7:27:30
*/
public static String changeDot(String attrvalue, int dot) {
BigDecimal db = new BigDecimal(attrvalue);
return String.valueOf(db.setScale(dot, BigDecimal.ROUND_HALF_UP).doubleValue());
}
public static void saveToFile(String fileName, InputStream in) throws IOException {
FileOutputStream fos = null;
BufferedInputStream bis = null;
int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
bis = new BufferedInputStream(in);
File f = new File(fileName);
if (!f.exists())//
{
File parentDir = new File(f.getParent());
if (!parentDir.exists())//
{
parentDir.mkdirs();
}
f.createNewFile();
}
fos = new FileOutputStream(fileName);
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
fos.close();
bis.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public static String parseTime(String timeValue, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String resultValue = "";
try {
long timeLongValue = Long.parseLong(timeValue);
if (timeLongValue > 0) {
Timestamp ts = new Timestamp(timeLongValue);
resultValue = sdf.format(ts);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultValue;
}
public static String inputStream2String(InputStream is)
throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/***
* 删除文件夹
*
* @param folderPath 文件夹完整绝对路径
*/
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 删除完里面所有内容
File myFilePath = new File(folderPath);
boolean b = myFilePath.delete(); // 删除空文件夹
if(!b){
log.error("删除文件失败,路径错误!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 删除指定文件夹下所有文件
*
* @param path
* 文件夹完整绝对路径
* @return
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);// 再删除空文件夹
flag = true;
}
}
return flag;
}
/**
* 查找类及其父类的所有属性
* @param clazz
* @return
*/
public static List<Field> getAllFields(Class clazz) {
List<Field> fields = Lists.newArrayList();
while (clazz != null) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
clazz = clazz.getSuperclass();
}
return fields;
}
/**
* 四舍五入
* @param d
* @param bitNum
* @return
*/
public static double getDouble(double d,int bitNum){
BigDecimal b = BigDecimal.valueOf(d);//增加计算精度的处理四舍弃五入
return b.setScale(bitNum, BigDecimal.ROUND_HALF_UP).doubleValue();//保留3位小数
}
/**
* 去掉数值末尾的0
* @param d
* @param bitNum
* @return
*/
public static String getDoubleString(double d,int bitNum){
BigDecimal b = BigDecimal.valueOf(d);//增加计算精度的处理四舍弃五入
return b.setScale(bitNum, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();//保留3位小数
}
public static String timestamp2Date(String str_num,String format ) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
if(StrUtil.isBlank(str_num)) str_num = "0";
if (str_num.length() == 13) {
String date = sdf.format(new Date(Long.parseLong(str_num)));
//LogUtil.debug("timestamp2Date"+ "将13位时间戳:" + str_num + "转化为字符串:", date);
return date;
} else if(!"0".equals(str_num)) {
String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
//LogUtil.debug("timestamp2Date" + "将10位时间戳:" + str_num + "转化为字符串:", date);
return date;
}else
return "";
}
}

View File

@ -0,0 +1,143 @@
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.centricsoftware.commons.utils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* 封装各种格式的编码解码工具类.
* 1.Commons-Codec的 hex/base64 编码
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
*
* @author calvin
* @version 2016-01-15
*/
public class EncodeUtils {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return new String(Hex.encodeHex(input));
}
/**
* Hex解码.
*/
public static byte[] decodeHex(String input) throws DecoderException {
return Hex.decodeHex(input.toCharArray());
}
/**
* Base64编码.
*/
public static String encodeBase64(byte[] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* Base64解码.
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input.getBytes());
}
/**
* Base64解码.
*/
public static String decodeBase64String(String input) {
try {
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* Base62编码
*/
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
}
return new String(chars);
}
/**
* Html 转码.
*/
public static String escapeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}
/**
* Html 解码.
*/
public static String unescapeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String escapeXml(String xml) {
return StringEscapeUtils.escapeXml10(xml);
}
/**
* Xml 解码.
*/
public static String unescapeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String urlDecode(String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
public static void main(String[] args){
System.out.println(EncodeUtils.encodeBase64("plm.2021.666"));
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,267 @@
package com.centricsoftware.commons.utils;
import jcifs.util.Base64;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* 从网络获取图片到本地
* 同类方法{@link cn.hutool.http.HttpUtil}
* @author Harry
* @version 1.0
* @since
*/
public class FileUtil {
/**
* 测试
* @param args
*/
public static void main(String[] args) {
String url = "http://www.baidu.com/img/baidu_sylogo1.gif";
String dest = "D:\\test\\image";
// String fileName = downloadImage(url,"D:\\test\\image");
// System.out.println(fileName);
// HttpUtil.downloadFile(url,dest);
}
public static String downloadImage(String url,String filePath){
if(!"".equals(url) && url != null){
byte[] btImg = getImageFromNetByUrl(url);
if(null != btImg && btImg.length > 0){
String fileName = url.substring(url.lastIndexOf("/")+1);
writeImageToDisk(btImg, filePath,fileName);
return filePath+fileName;
}
}
return null;
}
/**
* 将图片写入到磁盘
* @param img 图片数据流
* @param fileName 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String filePath, String fileName){
try {
File folder = new File(filePath);
folder.mkdirs();
File file = new File(filePath+fileName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("图片已经写入");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将图片写入到磁盘
* @param img 图片数据流
* @param filePath 文件保存时的路径
*/
public static void writeImageToDisk(byte[] img, String filePath){
try {
File file = new File(filePath);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("图片已经写入");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据地址获得数据的字节流
* @param strUrl 网络连接地址
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl){
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public static void write2File(String filename,String str){
try {
String strEncode = Base64.encode(str.getBytes());
byte[] bytes = strEncode.getBytes();
File file = new File(filename);
FileOutputStream fops = new FileOutputStream(file);
fops.write(bytes);
fops.flush();
fops.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static String byte2hex(byte[] b) // 二进制转字符串
{
StringBuffer sb = new StringBuffer();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1){
sb.append("0" + stmp);
}else{
sb.append(stmp);
}
}
return sb.toString();
}
public static byte[] hex2byte(String str) { // 字符串转二进制
if (str == null)
return null;
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1)
return null;
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static MultipartFile getMultipartFile(InputStream is, String fileName){
return getMultipartFile(is,fileName,"file");
}
public static MultipartFile getMultipartFile(InputStream is, String fileName,String item){
String dest = "c:/temp/" + fileName;
File file = cn.hutool.core.io.FileUtil.writeFromStream(is, new File(dest));
return getMultipartFile(file,item);
}
/**
* 输入流转MultipartFile
*
* @param fileName
* @param inputStream
* @return
*/
public static MultipartFile getMultipartFile(String fileName, InputStream inputStream) {
MultipartFile multipartFile = null;
try {
multipartFile = new MockMultipartFile(fileName, fileName,
ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return multipartFile;
}
/**
* 通过file获取MultipartFile
* 更新记录2025-02-25 xulin.xie 修复png透明底变更黑色底的问题
* @param file
* @return
*/
public static MultipartFile getMultipartFile(File file,String item) {
// DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
// MediaType.ALL_VALUE, true, file.getName());
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem(item,
MediaType.ALL_VALUE, true, file.getName());
try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
IOUtils.copy(input, os);
}catch (Exception e){
throw new IllegalArgumentException("Invalid file: " + e, e);
}
MultipartFile multi = new CommonsMultipartFile(fileItem);
return multi;
}
/**
* 通过inputStream获取MultipartFile
*
* @param inputstream 输入流
* @return
*/
public static MultipartFile getMultipartFileByStream(InputStream inputstream, String item) {
// DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
// MediaType.ALL_VALUE, true, file.getName());
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem(item,
MediaType.ALL_VALUE, true, "file");
try (OutputStream os = fileItem.getOutputStream()) {
IOUtils.copy(inputstream, os);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
return new CommonsMultipartFile(fileItem);
}
public static MultipartFile getNewMultipartFile(File file,String item) {
try {
FileInputStream input = new FileInputStream(file);
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(file.getName());
String contentType = MediaType.ALL_VALUE;
if ("image/png".equals(mimeType)) {
contentType = MediaType.IMAGE_PNG_VALUE;
}
MockMultipartFile multipartFile = new MockMultipartFile(
"file",
file.getName(),
contentType,
input
);
return multipartFile;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,198 @@
package com.centricsoftware.commons.utils;
import cn.hutool.extra.ftp.Ftp;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.SocketException;
/**
* Ftp上传下载工具类
* 同类方法 {@link cn.hutool.extra.ftp.Ftp}
* @author zheng.gong
* @date 2020/4/27
*/
public class FtpUtil {
public static void main(String[] args) throws IOException {
//匿名登录无需帐号密码的FTP服务器
Ftp ftp = new Ftp("172.0.0.1");
//进入远程目录
ftp.cd("/opt/upload");
//上传本地文件
ftp.upload("/opt/upload", cn.hutool.core.io.FileUtil.file("e:/test.jpg"));
//下载远程文件
ftp.download("/opt/upload", "test.jpg", cn.hutool.core.io.FileUtil.file("e:/test2.jpg"));
//关闭连接
ftp.close();
}
/**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
* @param ftpPassword
* FTP 登录密码
* @param ftpUserName
* FTP登录用户名
* @param ftpPort
* FTP端口 默认为21
* @return
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("未连接到FTP用户名或密码错误。");
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误请正确配置。");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/*
* 从FTP服务器下载文件
*
* @param ftpHost FTP IP地址
*
* @param ftpUserName FTP 用户名
*
* @param ftpPassword FTP用户名密码
*
* @param ftpPort FTP端口
*
* @param ftpPath FTP服务器中文件所在路径 格式 ftptest/aa
*
* @param localPath 下载到本地的位置 格式H:/download
*
* @param fileName 文件名称
*/
public static String downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
String ftpPath, String localPath, String fileName) {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
File localFile = new File(localPath + File.separatorChar + fileName);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(fileName, os);
os.close();
ftpClient.logout();
} catch (FileNotFoundException e) {
System.out.println("没有找到" + ftpPath + "文件");
e.printStackTrace();
} catch (SocketException e) {
System.out.println("连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取错误。");
e.printStackTrace();
}
return localPath + File.separatorChar + fileName;
}
/**
* Description: 向FTP服务器上传文件
*
* @param ftpHost
* FTP服务器hostname
* @param ftpUserName
* 账号
* @param ftpPassword
* 密码
* @param ftpPort
* 端口
* @param ftpPath
* FTP服务器中文件所在路径 格式 ftptest/aa
* @param fileName
* ftp文件名称
* @param input
* 文件流
* @return 成功返回true否则返回false
*/
public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
String ftpPath, String fileName, InputStream input) {
boolean success = false;
FTPClient ftpClient = null;
try {
int reply;
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return success;
}
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
ftpClient.storeFile(fileName, input);
input.close();
ftpClient.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 根据文件前缀找出ftp服务器上的完整文件名
**/
public static String getFileName(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String prefix) {
FTPClient ftpClient = null;
String filename = "";
try {
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
System.out.println("Path is:" + ftpPath);
FTPFile[] files = ftpClient.listFiles(ftpPath);
for (FTPFile file : files) {
if (file.isFile()) {
if (file.getName().startsWith(prefix)) {
filename = file.getName();
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
}

View File

@ -0,0 +1,121 @@
package com.centricsoftware.commons.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 图片工具类
* 同类方法{@link cn.hutool.core.img.ImgUtil}
* @author zheng.gong
* @date 2020/4/27
*/
public class ImageUtil {
public static void resize(String filePath, int height, int width) {
try {
// Thumbnails.of(filePath).size(1024, 1024).toFile(filePath);
resizePng(new File(filePath), width, height, true);
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(bi.getWidth(), bi.getHeight(), BufferedImage.SCALE_SMOOTH);
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// 获取Graphics2D
Graphics2D g2d = newImage.createGraphics();
// ---------- 增加下面的代码使得背景透明 -----------------
newImage = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = newImage.createGraphics();
// ---------- 背景透明代码结束 -----------------
if (width == itemp.getWidth(null)) {
g2d.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null),
itemp.getHeight(null), null, null);
} else {
g2d.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null),
null, null);
}
g2d.dispose();
ImageIO.write(newImage, "png", f);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void resizePng(File fromFile, int outputWidth, int outputHeight, boolean proportion) {
try {
BufferedImage bi2 = ImageIO.read(fromFile);
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (proportion) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth;
double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) ((bi2.getWidth(null)) / rate);
newHeight = (int) ((bi2.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = to.createGraphics();
to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = to.createGraphics();
@SuppressWarnings("static-access")
Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
g2d.drawImage(from, 0, 0, null);
g2d.dispose();
ImageIO.write(to, "png", fromFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void fillInSquare(String filePath) {
try {
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
int width = bi.getWidth();
int height = bi.getHeight();
// Image itemp = bi.getScaledInstance(width, height,
// BufferedImage.SCALE_SMOOTH);
Image itemp = bi;
BufferedImage image = null;
if (width >= height) {
image = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, width);
g.drawImage(itemp, 0, (width - height) / 2, width, height, Color.white, null);
g.dispose();
} else {
image = new BufferedImage(height, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, height, height);
g.drawImage(itemp, (height - width) / 2, 0, width, height, Color.white, null);
g.dispose();
}
itemp = image;
ImageIO.write((BufferedImage) itemp, "png", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
fillInSquare("C:\\C8\\Temp\\KA98308-11-03.jpg");
}
}

View File

@ -0,0 +1,257 @@
/**
* Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
*/
package com.centricsoftware.commons.utils;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 导入Excel文件支持XLSXLSX格式
* @author jeeplus
* @version 2016-03-10
*/
public class ImportExcel {
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 标题行号
*/
@Getter
private int headerNum;
/**
* 构造函数
* @param fileName 导入文件读取第一个工作表
* @param headerNum 标题行号数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum);
}
/**
* 构造函数
* @param file 导入文件对象读取第一个工作表
* @param headerNum 标题行号数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum)
throws InvalidFormatException, IOException {
this(file, headerNum, 0);
}
/**
* 构造函数
* @param fileName 导入文件
* @param headerNum 标题行号数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum, sheetIndex);
}
/**
* 构造函数
* @param file 导入文件对象
* @param headerNum 标题行号数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
}
/**
* 构造函数
* @param multipartFile 导入文件对象
* @param headerNum 标题行号数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}
/**
* 构造函数
* @param fileName 导入文件对象
* @param headerNum 标题行号数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
if (StringUtils.isBlank(fileName)){
throw new RuntimeException("导入文档为空!");
}else if(fileName.toLowerCase().endsWith("xls")){
this.wb = new HSSFWorkbook(is);
}else if(fileName.toLowerCase().endsWith("xlsx")){
this.wb = new XSSFWorkbook(is);
}else{
throw new RuntimeException("文档格式不正确!");
}
if (this.wb.getNumberOfSheets()<sheetIndex){
throw new RuntimeException("文档中没有工作表!");
}
this.sheet = this.wb.getSheetAt(sheetIndex);
this.headerNum = headerNum;
}
/**
* 获取行对象
* @param rownum
* @return
*/
public Row getRow(int rownum){
return this.sheet.getRow(rownum);
}
/**
* 获取数据行号
* @return
*/
public int getDataRowNum(){
return headerNum+1;
}
/**
* 获取最后一个数据行号
* @return
*/
public int getLastDataRowNum(){
return this.sheet.getLastRowNum()+headerNum;
}
/**
* 获取最后一个列号
* @return
*/
public int getLastCellNum(){
return this.getRow(headerNum).getLastCellNum();
}
/**
* 获取单元格值
* @param row 获取的行
* @param column 获取单元格列号
* @return 单元格值
*/
public Object getCellValue(Row row, int column) {
Object val = "";
Cell cell = row.getCell(column);
if (cell != null) {
switch (cell.getCellType()) {
case NUMERIC:
// 当excel 中的数据为数值或日期是需要特殊处理
if (HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(d);
SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
val = dformat.format(date);
} else {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);// true时的格式1,234,567,890
val = nf.format(cell.getNumericCellValue());// 数值类型的数据为double所以需要转换一下
}
break;
case BOOLEAN:
val = cell.getBooleanCellValue();
break;
case ERROR:
val = cell.getErrorCellValue();
break;
case FORMULA: // 公式
try {
val = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
val = String.valueOf(cell.getRichStringCellValue());
}
break;
default:
val = cell.getStringCellValue();
}
}
return val;
}
/**
* 当导入的表格不是entity对象时调用此方法
* @return
*/
public List<List<String>> getCustomDataList(){
List<List<String>> dataList = new ArrayList<>();
for (int i = this.getDataRowNum(); i <= this.getLastDataRowNum(); i++) {
Row row = this.getRow(i);
List<String> dataRow = new ArrayList<>();
for(int j = 0; j < this.getLastCellNum(); j++){
dataRow.add(this.getCellValue(row, j).toString());
}
dataList.add(dataRow);
}
return dataList;
}
/**
* 删除行
* @param startRow 开始行
* @param endRow 结束行
*/
public void deleteRow(int startRow,int endRow,int n){
this.sheet.shiftRows(startRow,endRow,n);
}
// /**
// * 导入测试
// */
// public static void main(String[] args) throws Throwable {
//
// ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
//
// for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
// Row row = ei.getRow(i);
// for (int j = 0; j < ei.getLastCellNum(); j++) {
// Object val = ei.getCellValue(row, j);
// System.out.print(val+", ");
// }
// System.out.print("\n");
// }
//
// }
}

View File

@ -0,0 +1,36 @@
package com.centricsoftware.commons.utils;
import javax.servlet.http.HttpServletRequest;
/**
* 获取前台的IP地址
*/
public class IpUtil {
static final String UNKNOWN = "unknown";
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return UNKNOWN;
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
//System.out.println(ip);
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}

View File

@ -0,0 +1,349 @@
package com.centricsoftware.commons.utils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
/**
*
* JSON工具类
* 同类方法{@link cn.hutool.json.JSONUtil}
* @author GHUANG
* @version 2016年3月28日 下午8:15:11
*
*
*/
public class JsonHelper {
/**
*
* @param javaBean
* @return
* @author GHUANG
* @version 2016年3月28日 下午8:15:27
*/
public static Map toMap(Object javaBean) {
Map result = new HashMap();
Method[] methods = javaBean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("get")) {
String field = method.getName();
field = field.substring(field.indexOf("get") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
Object value = method.invoke(javaBean, (Object[]) null);
result.put(field, null == value ? "" : value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static JSONArray getJAfromList(List<HashMap> list) throws Exception {
JSONArray ja = new JSONArray();
for (HashMap<String, String> map : list) {
JSONObject json = new JSONObject();
for (Entry<String, String> gmap : map.entrySet()) {
String key = gmap.getKey();
String value = gmap.getValue();
json.put(key, value);
}
ja.put(json);
}
return ja;
}
public static JSONObject convertJS(JSONObject js) throws Exception {
JSONObject json = new JSONObject();
Iterator it = js.keys();
while (it.hasNext()) {
String key = (String) it.next();
String value = js.getString(key);
json.put(value, key);
}
return json;
}
public static JSONObject getJsonfromMap(HashMap<String, String> map) throws Exception {
JSONObject json = new JSONObject();
for (Entry<String, String> gmap : map.entrySet()) {
String key = gmap.getKey();
String value = gmap.getValue();
json.put(key, value);
}
return json;
}
/**
*
* @param json
* @return
* @author GHUANG
* @version 2019年5月15日 上午11:13:46
*/
public static String getJsonToXml(JSONObject json) {
Iterator<String> it = json.keys();
StringBuffer sb = new StringBuffer();
while (it.hasNext()) {
String key = it.next();
String value = json.optString(key);
try {
if (value.startsWith("[")) {
JSONArray ja = new JSONArray(value);
sb.append("<").append(key).append(">");
if (ja.length() > 0) {
for (int j = 0; j < ja.length(); j++) {
JSONObject sjs = ja.getJSONObject(j);
if (key.equals("JSON")) { // 去掉非
sb.append("<").append(key).append(">");
String sbstr = getJsonToXml(sjs);
sb.append(sbstr);
sb.append("</").append(key).append(">");
} else {
String sbstr = getJsonToXml(sjs);
sb.append(sbstr);
}
}
}
sb.append("</").append(key).append(">");
} else if (value.startsWith("{")) {
JSONObject jsonSon = new JSONObject(value);
sb.append("<").append(key).append(">");
sb.append(getJsonToXml(jsonSon));
sb.append("</").append(key).append(">");
} else {
sb.append("<").append(key).append(">").append(value).append("</").append(key)
.append(">");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
*
* @param jsonString
* @return
* @throws JSONException
* @author GHUANG
* @version 2016年3月28日 下午8:15:44
*/
public static HashMap<String, String> toMap(String jsonString) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
HashMap<String, String> result = new HashMap<String, String>();
Iterator iterator = jsonObject.keys();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
value = jsonObject.getString(key);
result.put(key, value);
}
return result;
}
/**
*
* @param jsonString
* @return
* @throws JSONException
* @author GHUANG
* @version 2016年3月28日 下午8:15:44
*/
public static ArrayList toMapfromArray(String jsonString) throws JSONException {
JSONArray jsonObject = new JSONArray(jsonString);
ArrayList infoList = new ArrayList();
for (int i = 0; i < jsonObject.length(); i++) {
String jobj = jsonObject.getJSONObject(i).toString();
HashMap<String, String> map = JsonHelper.toMap(jobj);
// System.out.println("map="+map.toString());
infoList.add(map);
}
return infoList;
}
/**
*
* @param bean
* @return
* @author GHUANG
* @version 2016年3月28日 下午8:15:51
*/
public static JSONObject toJSON(Object bean) {
return new JSONObject(toMap(bean));
}
/**
*
* @param javabean
* @param data
* @return
* @author GHUANG
* @version 2016年3月28日 下午8:15:57
*/
public static Object toJavaBean(Object javabean, Map data) {
Method[] methods = javabean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("set")) {
String field = method.getName();
field = field.substring(field.indexOf("set") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
method.invoke(javabean, data.get(field));
}
} catch (Exception e) {
}
}
return javabean;
}
/**
* 通过JSONObject获取对应的key值(String)
*
* @param jsonObj
* @param key
* @return
*/
private static String getJSONString(JSONObject jsonObj, String key) {
String retString = "";
try {
Object obj = jsonObj.get(key);
if (obj != null) {
retString = String.valueOf(obj);
}
} catch (Exception e) {
// TODO: handle exception
retString = "";
}
return retString;
}
/**
*
* @param javabean
* @param jsonString
* @throws ParseException
* @throws JSONException
* @author GHUANG
* @version 2016年3月28日 下午8:16:04
*/
public static void toJavaBean(Object javabean, String jsonString)
throws ParseException, JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
Map map = toMap(jsonObject.toString());
toJavaBean(javabean, map);
}
public static HashMap getJsonToMap(JSONObject json) throws Exception {
HashMap map = new HashMap();
for (Iterator<?> it = json.keys(); it.hasNext();) {
String key = (String) it.next();
String value = json.getString(key);
map.put(key, value);
}
return map;
}
public static HashMap getMapfromJson(JSONObject json) throws Exception {
HashMap map = new HashMap();
for (Iterator<?> it = json.keys(); it.hasNext();) {
String key = (String) it.next();
String value = json.getString(key);
map.put(key, value);
}
return map;
}
public static ArrayList getListfromJa(JSONArray ja) throws Exception {
ArrayList list = new ArrayList();
for (int i = 0; i < ja.length(); i++) {
JSONObject json = ja.getJSONObject(i);
HashMap<String, Object> map = getMapfromJson(json);
list.add(map);
}
return list;
}
public static JSONObject parseJS(JSONObject a, JSONObject b) throws Exception {
Iterator it = a.keys();
while (it.hasNext()) {
String key = (String) it.next();
Object value = a.get(key);
if (value instanceof String) {
b.put(key, value);
} else if (value instanceof JSONArray) {
JSONArray ja = (JSONArray) value;
b.put(key, ja);
}
}
return b;
}
public static Date[] getJsonToDateArray(String jsonString) throws ParseException, JSONException {
JSONArray jsonArray = new JSONArray(jsonString);
Date[] dateArray = new Date[jsonArray.length()];
String dateString;
Date date;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < jsonArray.length(); i++) {
dateString = jsonArray.getString(i);
try {
date = sdf.parse(dateString);
dateArray[i] = date;
} catch (Exception e) {
e.printStackTrace();
}
}
return dateArray;
}
}

View File

@ -0,0 +1,225 @@
package com.centricsoftware.commons.utils;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
@Slf4j
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
private static ObjectMapper NULL_STRING_MAPPER;
/**
* 动态排除的过滤器key
*/
private static final String DYNA_EXCLUDES = "dynaExcludes";
@JsonFilter(DYNA_EXCLUDES)
interface DynamicExclude {
}
static {
// 如果存在未知属性则忽略不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//允许空对象转成json
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 允许key没有双引号
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 允许key有单引号
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 防止double变成科学计数法
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(CommonUtil.YMD_HMS_DASH)));
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(CommonUtil.YMD_HMS_DASH)));
javaTimeModule.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(CommonUtil.YMD_DASH)));
javaTimeModule.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(CommonUtil.YMD_DASH)));
javaTimeModule.addDeserializer(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern(CommonUtil.HMS_DASH)));
javaTimeModule.addSerializer(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern(CommonUtil.HMS_DASH)));
mapper.registerModule(javaTimeModule);
NULL_STRING_MAPPER = mapper.copy();
NULL_STRING_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
NULL_STRING_MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object param, JsonGenerator jsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException {
jsonGenerator.writeString("");
}
});
}
/**
* 转换为json字符串
*/
public static String toJSONString(Object obj) {
if (Objects.isNull(obj)) {
return null;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("转换对象到json失败, 参数:" + obj);
}
}
/**
* 转换为json字符串. null会转成""
*/
public static String toJSONStringNull2Empty(Object obj) {
if (Objects.isNull(obj)) {
return null;
}
try {
return NULL_STRING_MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("转换对象到json失败, 参数:" + obj);
}
}
/**
* 转换为json字符串, 排除忽略的字段
*/
public static String toJSONString(Object obj, String[] ignoreFields) {
if (ArrayUtils.isEmpty(ignoreFields)) {
return toJSONString(obj);
}
try {
ObjectMapper objectMapper = mapper.copy().setFilterProvider(
new SimpleFilterProvider().addFilter(DYNA_EXCLUDES,
SimpleBeanPropertyFilter.serializeAllExcept(ignoreFields)));
objectMapper.addMixIn(obj.getClass(), DynamicExclude.class);
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("转换对象到json失败, 参数:" + obj);
}
}
/**
* 转换为json字符串, 排除忽略的字段
*/
public static String toJSONStringNull2Empty(Object obj, String[] ignoreFields) {
if (ArrayUtils.isEmpty(ignoreFields)) {
return toJSONStringNull2Empty(obj);
}
try {
ObjectMapper objectMapper = NULL_STRING_MAPPER.copy().setFilterProvider(
new SimpleFilterProvider().addFilter(DYNA_EXCLUDES,
SimpleBeanPropertyFilter.serializeAllExcept(ignoreFields)));
objectMapper.addMixIn(obj.getClass(), DynamicExclude.class);
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("转换对象到json失败, 参数:" + obj);
}
}
/**
* 转换为json字节数组
*/
public static byte[] toJSONBytes(Object obj) {
if (Objects.isNull(obj)) {
return new byte[0];
}
try {
return mapper.writeValueAsBytes(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("转换对象到json失败, 参数:" + obj, e);
}
}
/**
* 转换为java对象
*/
public static <T> T parseObject(String json, Class<T> clazz) {
if (org.apache.commons.lang3.StringUtils.isBlank(json)) {
return null;
}
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
throw new RuntimeException("转换字符串到对象失败json: " + json);
}
}
/**
* 转换为java对象
*/
public static <T> T parseObject(String json, TypeReference<T> ref) {
if (StringUtils.isBlank(json)) {
return null;
}
try {
return mapper.readValue(json, ref);
} catch (IOException e) {
throw new RuntimeException("转换字符串到对象失败json: " + json);
}
}
/**
* 转换为对象集合
*/
public static <T> List<T> parseArray(String json, Class<T> clazz) {
try {
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
return mapper.readValue(json, javaType);
} catch (IOException e) {
throw new RuntimeException("转换字符串到对象数组失败json: " + json);
}
}
/**
* 转换为集合
*
*/
@SuppressWarnings("unchecked")
public static List<LinkedHashMap<String, Object>> parseArray(String json) {
try {
return mapper.readValue(json, List.class);
} catch (IOException e) {
throw new RuntimeException("转换字符串到对象数组失败json: " + json);
}
}
/**
* 获取Mapper
*
*/
public static ObjectMapper getMapper() {
return mapper;
}
}

View File

@ -0,0 +1,181 @@
package com.centricsoftware.commons.utils;
import com.centricsoftware.config.entity.CsProperties;
import lombok.extern.slf4j.Slf4j;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* 邮件工具类同类型工具类{@link cn.hutool.extra.mail.Mail},按个人喜好使用即可
*
* @ClassName: MailUtil
* @Description: 发送Email
* @author: Harry
* @date: 2016-5-30 下午9:42:56
*
*/
@Slf4j
public class MailUtil {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// sendMail("mail.bestseller.com.cn","noreply@bestseller.com.cn","PLM
// Admin","bs_stAff_123$","harry.liang@centricsoftware.com","PO:1631P0100087C质检已完成请给出QAC决策","PO:1631P0100087C质检已完成请给出QAC决策<BR/>PO:1631P0100087C质检已完成请给出QAC决策");
// testSendMail();
}
public static void testSendMail( String mailToUsers) throws Exception{
CsProperties properties = SpringUtil.getBean(CsProperties.class);
System.out.println("mailToUsers=" + mailToUsers);
String poNumber = "PO12390393245";
String qaDecision = "不合格/Fail";
String wareHouse = "050A";
String vDecision = "不合格/Fail";
String mDecision = "不合格/Fail";
String comment = "不合格/Fail";
mailToUsers = "harry.liang@centricsoftware.com;jief@bestseller.com.cn";
try {
if (!"".equals(mailToUsers) && !";".equals(mailToUsers)) {
String title = "PO:" + poNumber + " 已经完成质检(" + qaDecision + ")请尽快提供QAC决策. QA Inspection has been done("
+ qaDecision + "), please make QAC Decision ASAP. ";
String content = "Dear Buyer,<BR/>";
content += "PO Number: " + poNumber + "<BR/>";
content += "Ware House ID:" + wareHouse + "<BR/>";
content += "QAV Result: " + vDecision + "<BR/>";
content += "QAM Result: " + mDecision + "<BR/>";
content += "QA Decision: " + qaDecision + "<BR/>";
content += "QA Comments: " + comment + "<BR/>";
MailUtil.sendMail(properties.getValue("mail.host"), properties.getValue("mail.sender"),
properties.getValue("mail.senderName"), properties.getValue("mail.senderPwd"), mailToUsers,
title, content);
System.out.println("Sent Mail to =" + mailToUsers);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Fail to send Mail to =" + mailToUsers);
}
}
public static void testMail() throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "mail.bestseller.com.cn");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
// 使用JavaMail发送邮件的5个步骤
// 1创建session
Session session = Session.getInstance(prop);
// 开启Session的debug模式这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
// 2通过session得到transport对象
Transport ts = session.getTransport();
// 3使用邮箱的用户名和密码连上邮件服务器发送邮件时发件人需要提交邮箱的用户名和密码给smtp服务器用户名和密码都通过验证之后才能够正常发送邮件给收件人
ts.connect("mail.bestseller.com.cn", "noreply@bestseller.com.cn", "bs_stAff_123$");
// 4创建邮件
Message message = createSimpleMail(session);
// 5发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
/**
* 发送邮件
*
* @param mailHost
* @param sender
* @param senderName
* @param senderPwd
* @param toUsers
* 多个用户使用分号分割
* @param title
* @param content
*/
public static String sendMail(String mailHost, String sender, String senderName, String senderPwd, String toUsers,
String title, String content) {
Properties prop = new Properties();
prop.setProperty("mail.host", mailHost);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
Transport ts;
String result = "success";
try {
// 使用JavaMail发送邮件的5个步骤
// 1创建session
Session session = Session.getInstance(prop);
// 开启Session的debug模式这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
// 2通过session得到transport对象
ts = session.getTransport();
// 3使用邮箱的用户名和密码连上邮件服务器发送邮件时发件人需要提交邮箱的用户名和密码给smtp服务器用户名和密码都通过验证之后才能够正常发送邮件给收件人
ts.connect(mailHost, sender, senderPwd);
// 4创建邮件
Message message = new MimeMessage(session);
// 指明邮件的发件人
InternetAddress address = new InternetAddress(sender);
address.setPersonal(senderName);
message.setFrom(address);
// 指明邮件的收件人现在发件人和收件人是一样的那就是自己给自己发
if (toUsers.indexOf(";") >= 0) {
String[] toUsersList = toUsers.split(";");
for (String toUser : toUsersList) {
toUser = toUser.trim();
if (!"".equals(toUser)) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toUser));
}
}
} else {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toUsers));
}
// 邮件的标题
message.setSubject(title);
// 邮件的文本内容
message.setContent(content, "text/html;charset=UTF-8");
// 5发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error("", e);
result = "fail";
}
return result;
}
/**
* @Method: createSimpleMail
* @Description: 创建一封只包含文本的邮件
* @Anthor:Harry Liang
*
* @param session
* @return
* @throws Exception
*/
public static MimeMessage createSimpleMail(Session session)
throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
InternetAddress address = new InternetAddress("noreply@bestseller.com.cn");
address.setPersonal("PLM Admin");
message.setFrom(address);
// 指明邮件的收件人现在发件人和收件人是一样的那就是自己给自己发
message.addRecipient(Message.RecipientType.TO, new InternetAddress("harry.liang@centricsoftware.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("jief@bestseller.com.cn"));
// 邮件的标题
message.setSubject("邮件发送个测试");
// 邮件的文本内容
message.setContent("你好啊!", "text/html;charset=UTF-8");
// 返回创建好的邮件对象
return message;
}
}

View File

@ -0,0 +1,55 @@
package com.centricsoftware.commons.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class MarkImageUtil {
/**
* 添加图标在图片上
* @author liaochangjiang
* @since 2024-02-21 11:27
*/
public static InputStream addImgMark(Image con, int iconWidth, int iconHeight, Image img, int x, int y,int width, int height) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.getDeviceConfiguration().createCompatibleImage(img.getWidth(null), img.getHeight(null), Transparency.TRANSLUCENT);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
float clarity = 1f;//透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, clarity));
g.drawImage(con.getScaledInstance(iconWidth, iconHeight, Image.SCALE_SMOOTH), x, y, null);
g.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, "png", os);
// 最终返回的文件流
return new ByteArrayInputStream(os.toByteArray());
}
/**
* 添加文字在图片上
* @author liaochangjiang
* @since 2024-02-21 11:27
*/
public static InputStream addTextMark(Image img, int x, int y,int width, int height,String martText, Color color, Font font) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.getDeviceConfiguration().createCompatibleImage(img.getWidth(null), img.getHeight(null), Transparency.TRANSLUCENT);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
if(null != color) {
g.setColor(color);
}
if(null != font){
g.setFont(font);
}
g.drawString(martText, x, y);
g.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, "png", os);
// 最终返回的文件流
return new ByteArrayInputStream(os.toByteArray());
}
}

View File

@ -0,0 +1,21 @@
package com.centricsoftware.commons.utils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.centricsoftware.commons.dto.PlmPageReqVo;
import com.centricsoftware.config.cons.Constants;
public class PageUtil {
/**
* 构建分页对象
*
* @author liaochangjiang
* @since 2021-01-18 15:59:16
*/
public static <T> Page<T> buildPageParam(PlmPageReqVo<?> req, Class<T> clazz) {
final Page<T> page = new Page<>(req.getPageNum(), req.getPageSize());
if (page.getSize() > Constants.PAGE_MAX_LIMIT) {
page.setMaxLimit(page.getSize());
}
return page;
}
}

View File

@ -0,0 +1,197 @@
package com.centricsoftware.commons.utils;
import com.centricsoftware.config.entity.CsProperties;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import java.io.*;
/**
* 向共享盘上传递图片信息
* 同类方法 {@link cn.hutool.extra.ftp.Ftp}
* @author Harry
*
*/
public class SMBFileUtil {
public String fName = "";
public String fPassword = "";
public String fHost = "";
public String fFolder = "";
public SMBFileUtil(String userName, String password, String host,String folder){
this.fName = userName;
this.fPassword = password;
this.fHost = host;
this.fFolder = folder;
}
public SMBFileUtil(){
CsProperties properties = SpringUtil.getBean(CsProperties.class);
String userName = properties.getValue("cs.imageserver.username");
String password = properties.getValue("cs.imageserver.password");
String host = properties.getValue("cs.imageserver.host");
String folder = properties.getValue("cs.imageserver.folder");
this.fName = userName;
this.fPassword = password;
this.fHost = host;
this.fFolder = folder;
}
public String uploadFile(File localFile){
InputStream in = null;
OutputStream out = null;
String filepath = "";
try {
//获取图片
String remotePhotoUrl = "smb://"+this.fHost+"/"+this.fFolder; //存放图片的共享目录
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",this.fName,this.fPassword);
//SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS_");
SmbFile remoteFile = new SmbFile(remotePhotoUrl + "/" + localFile.getName(),auth);
remoteFile.connect(); //尝试连接
//如果远程可以连接那就判断先父节点目录是否存在不存在就创建
SmbFile parentDir = new SmbFile(remoteFile.getParent(),auth);
if (!parentDir.exists())
{
parentDir.mkdirs();
}
filepath = "http://"+this.fHost+"/"+this.fFolder.replace("eeka", "")+"/"+localFile.getName();
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //刷新缓冲的输出流
}
catch (Exception e) {
String msg = "发生错误:" + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
return filepath;
}
public static void uploadFile(File localFile,String userName, String password, String host,String folder){
InputStream in = null;
OutputStream out = null;
try {
//获取图片
String remotePhotoUrl = "smb://"+host+"/"+folder; //存放图片的共享目录
//SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS_");
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",userName,password);
SmbFile remoteFile = new SmbFile(remotePhotoUrl + "/" + localFile.getName(),auth);
remoteFile.connect(); //尝试连接
//如果远程可以连接那就判断先父节点目录是否存在不存在就创建
SmbFile parentDir = new SmbFile(remoteFile.getParent(),auth);
if (!parentDir.exists())
{
parentDir.mkdirs();
}
System.out.println(remotePhotoUrl+"=connected");
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //刷新缓冲的输出流
}
catch (Exception e) {
e.printStackTrace();
String msg = "发生错误:" + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}
/**
* 下载文件
* @return
*/
public byte[] downloadFile(String fileName){
InputStream in = null ;
ByteArrayOutputStream out = null ;
try {
//创建远程文件对象
String remotePhotoUrl = "smb://"+this.fHost+"/"+this.fFolder+"/"+fileName;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",this.fName,this.fPassword);
SmbFile remoteFile = new SmbFile(remotePhotoUrl,auth);
remoteFile.connect(); //尝试连接
//如果远程可以连接那就判断先父节点目录是否存在不存在就创建
SmbFile parentDir = new SmbFile(remoteFile.getParent(),auth);
if (!parentDir.exists())
{
parentDir.mkdirs();
}
//创建文件流
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new ByteArrayOutputStream((int)remoteFile.length());
//读取文件内容
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = in.read(buffer, 0, buffer.length)) != - 1) {
out.write(buffer, 0, len);
}
out.flush(); //刷新缓冲的输出流
return out.toByteArray();
}
catch (Exception e) {
String msg = "下载远程文件出错:" + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
return null;
}
public static void main(String[] args) {
uploadFile(new File("D:\\C8\\C8Test.model.xml"), "eeka", "Gst#2017", "10.7.121.10", "eeka/centric/");
}
}

View File

@ -0,0 +1,326 @@
/**
* @author GHUANG
* @version 2016年3月28日 下午5:48:18
*
*/
package com.centricsoftware.commons.utils;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HashMap;
/**
* 发送http请求工具类
* 同类方法{@link cn.hutool.http.HttpUtil}
* @author zheng.gong
* @date 2020/4/27
*/
public class ServicesUtil {
public static String HtmLog = "ConnectHtmLog";
static HashMap<String, String> initmap = null;
static {
initmap = new HashMap();
initmap.put("0", "");
initmap.put("1004", "Exception:服务器网络异常,请稍后重试");
initmap.put("1001", "Exception:请求参数错误");
initmap.put("1002", "Exception:该用户不存在");
initmap.put("1003", "Exception:该sign签名不合法");
initmap.put("1005", "Exception:SCM错误!");
initmap.put("1006", "Exception:SCM错误!");
initmap.put("1007", "Exception:网络连接错误!");
initmap.put("1008", "Exception:SCM错误!");
initmap.put("1009", "Exception:SCM错误!");
}
/**
* REST
*
* @param targetURL
* @param url
* @param typeId
* @return
* @author GHUANG
* @version 2019年4月20日 上午7:26:42
*/
public static String getData(String targetURL, String url, String typeId) {
//
String output = "";
try {
URL restServiceURL = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConnection.setRequestProperty("Charset", "UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String line;
while ((line = responseBuffer.readLine()) != null) {
output = output + line;
}
httpConnection.disconnect();
System.out.println("get Server Success:\n" + output);
if (output.indexOf("{") > 0) {
output = output.substring(output.indexOf("{"), output.lastIndexOf("}") + 1);
}
} catch (Exception e) {
StackTraceElement[] stackArray = e.getStackTrace();
for (int i = 0; i < stackArray.length; i++) {
StackTraceElement element = stackArray[i];
}
e.printStackTrace();
output = "Exception when PLM try to connect K3 ";
}
return output;
}
// static void callWebService(String param, String url, String user, String psd) throws AxisFault {
// System.out.println("call begin.....");
// RPCServiceClient serviceClient = new RPCServiceClient();
// Options options = serviceClient.getOptions();
// EndpointReference targetEPR = new EndpointReference(url);
// options.setTo(targetEPR);
// options.setManageSession(true);
// options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, true);
// options.setTimeOutInMilliSeconds(600000L);
// options.setUserName("connuser");
// options.setPassword("a87654321");
// // String response = "application/json ";
// Object[] opAddEntryArgs = new Object[] { param };
// Class[] classes = new Class[] { String.class };
// QName opAddEntry = new QName("http://ws.apache.org/axis2", "receive");
// System.out.println("result=" + serviceClient.invokeBlocking(opAddEntry, opAddEntryArgs, classes)[0]);
// System.out.println("call end...");
// }
/**
* REST支持
*
* @param targetURL
* @param jsonarray
* @param typeId
* @return
* @author GHUANG
* @version 2019年4月20日 上午7:26:30
*/
public static String postData(String targetURL, String jsonarray, String user, String password) {
String remsg = "";
HttpURLConnection httpConnection = null;
try {
System.out.println(targetURL);
URL targetUrl = new URL(targetURL);
System.out.println(user + "----" + password);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setUseCaches(false);
// 1.4的问题必须有SOAPAction
httpConnection.setRequestProperty("SOAPAction", "application/soap+xml; charset=utf-8");
httpConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConnection.setRequestProperty("Charset", "UTF-8");
byte[] requestStringBytes = jsonarray.getBytes(StandardCharsets.UTF_8);
httpConnection.setRequestProperty("Content-length", "" + requestStringBytes.length);
String users = user + ":" + password;
httpConnection.addRequestProperty("Authorization",
"Basic " + new String(Base64.encodeBase64(users.getBytes())));
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.flush();
outputStream.close();
if (httpConnection.getResponseCode() != 200) {
InputStream err = httpConnection.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(err, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode() + ",exception info" + sb.toString());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
//
// String line;
// System.out.println("Output from Server:\n");
// while ((line = responseBuffer.readLine()) != null) {
// System.out.println(line);
// }
responseBuffer.close();
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
remsg = e.getMessage();
if (remsg.contains("refused")) {
remsg = "对方接口拒绝连接请求!";
}
remsg = "Exception:" + remsg;
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return remsg;
}
/**
* REST支持SOAPxml格式param
*
* @param targetURL
* @param param
* @param user
* @param password
* @return
* @author GHUANG
* @version 2019年4月20日 上午7:26:30
*/
public static String putData(String targetURL, String param, String user, String password)
throws Exception {
String result = "";
HttpURLConnection con = null;
try {
long t1 = System.currentTimeMillis(); // 执行开始时间记录
URL url = new URL(targetURL);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(30 * 60 * 1000);
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
// con.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8; ");
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("Connection", "Keep-Alive");
con.setDoInput(true);
con.setDoOutput(true);
// con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// con.setRequestProperty("Charset", "UTF-8");
// con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
con.setRequestMethod("POST");
con.setUseCaches(false);
String users = user + ":" + password;
con.addRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(users.getBytes())));
con.connect();
// param = URLEncoder.encode(param, "utf-8");
OutputStream os = con.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os, StandardCharsets.UTF_8);
// String utf8String = new String(param.getBytes(), "utf-8");
// NodeUtil.outInfo("-----" + con.getContentEncoding() + "", HtmLog);
out.write(param);
out.flush();
out.close();
System.out.println(con.getResponseCode());
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
br.close();
} else {
InputStream err = con.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(err, StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
throw new RuntimeException("Failed : HTTP error code : "
+ con.getResponseCode() + ",exception info" + sb.toString());
}
con.disconnect();
} catch (Exception e) {
result = e.getMessage();
} finally {
if (con != null) {
con.disconnect();
}
}
return result;
}
/**
* 生成sign
*
* @param appkey
* @param secret
* @param sign_method
* @return
*/
public static String getSign(String epid, String appkey, String secret, String timestamp, String jsonStr) {
if (jsonStr.length() == 0) {
return "";
}
String paramString = epid + appkey + secret + timestamp + jsonStr;
String sign = "";
sign = byte2hex(encryptMD5(paramString, "UTF-8"));
return sign;
}
/**
* MD5加密
*
* @param data
* 字符串
*
* @param format
* 数据编码方式UTF-8GBK
* @return byte[]字节数组
* @throws IOException
*/
public static byte[] encryptMD5(String data, String format) {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.getBytes(format));
bytes = md.digest();
} catch (GeneralSecurityException gse) {
gse.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return bytes;
}
public static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString().toLowerCase();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// freezeMaterial();
System.out.println("---" + getData("http://192.168.37.133/plmservice/services/ESHub/pushChangeData?url=111" +
"&attrname=222&attrvalue=22211&flag=y", "", ""));
}
}

View File

@ -0,0 +1,88 @@
package com.centricsoftware.commons.utils;
/**
* Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
*/
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
*/
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static final Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()){
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
public static String getStatic(){
return SpringContextHolder.getApplicationContext().getApplicationName()+ "/static";
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy(){
SpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}

View File

@ -0,0 +1,43 @@
package com.centricsoftware.commons.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring工具类只有两个功能即获取容器中注册的bean向容器中注册bean
* @author zheng.gong
* @date 2020/4/27
*/
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}

View File

@ -0,0 +1,616 @@
/**
* Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
*/
package com.centricsoftware.commons.utils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
*
* @author jeeplus
* @version 2016-05-22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static byte[] getBytes(String str) {
if (str != null) {
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
} else {
return null;
}
}
/**
* 转换为字节数组
*
* @param bytes
* @return
*/
public static String toString(byte[] bytes) {
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)) {
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 替换为手机识别的HTML去掉样式及属性保留回车
*
* @param html
* @return
*/
public static String replaceMobileHtml(String html) {
if (html == null) {
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 替换为手机识别的HTML去掉样式及属性保留回车
*
* @param txt
* @return
*/
public static String toHtml(String txt) {
if (txt == null) {
return "";
}
return replace(replace(EncodeUtils.escapeHtml(txt), "\n", "<br/>"), "\t", "&nbsp; &nbsp; ");
}
/**
* 缩略字符串不区分中英文字符
*
* @param str 目标字符串
* @param length 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
return "";
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
}
StringBuffer result = new StringBuffer();
int n = 0;
char temp;
boolean isCode = false; // 是不是HTML代码
boolean isHTML = false; // 是不是HTML特殊字符,&nbsp;
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
if (n <= length - 3) {
result.append(temp);
} else {
result.append("...");
break;
}
}
// 取出截取字符串中的HTML标记
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
// 去掉不需要结素标记的HTML标记
temp_result = temp_result.replaceAll(
"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
"");
// 去掉成对的HTML标记
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
// 用正则表达式取出标记
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List<String> endHTML = Lists.newArrayList();
while (m.find()) {
endHTML.add(m.group(1));
}
// 补全不成对的HTML标记
for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("</");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val) {
if (val == null) {
return 0D;
}
try {
return Double.valueOf(trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(Object val) {
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val) {
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val) {
return toLong(val).intValue();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 转换为JS获取对象值生成三目运算返回结果
*
* @param objectString 对象串 例如row.user.id
* 返回!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for (int i = 0; i < vals.length; i++) {
val.append("." + vals[i]);
result.append("!" + (val.substring(1)) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}
/**
* 将字符串首字母转大写
*
* @param str
* @return
*/
public static String firstUpperCase(String str) {
if ((str == null) || (str.length() == 0))
return str;
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
/**
* 将字符串首字母转小写
*
* @param str
* @return
*/
public static String firstLowerCase(String str) {
if ((str == null) || (str.length() == 0))
return str;
char[] ch = str.toCharArray();
if (ch[0] >= 'A' && ch[0] <= 'Z') {
ch[0] = (char) (ch[0] + 32);
}
return new String(ch);
}
/***
* 截取字符串 里面的数字
*
* @param str
* @param breakflag 遇到非字符串是否立即终止
* @return
* @date:2018年7月10日
* @author:wuxiaoting
*/
public static String getNumeric(String str, boolean breakflag) {
StringBuilder sBuilder = new StringBuilder(20);
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
if (breakflag)
break;
continue;
}
sBuilder.append(str.charAt(i));
}
return sBuilder.toString();
}
/**
* 利用正则表达式判断字符串是否是数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (StringUtils.isBlank(str))
return false;
Pattern pattern = Pattern.compile("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
Matcher isNum = pattern.matcher(str);
return isNum.matches();
}
public static boolean isInteger(String str) {
if (StringUtils.isBlank(str))
return false;
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
return isNum.matches();
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable e) {
if (e == null){
return "";
}
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 检查Email格式
* @param email
* @return
*/
public static boolean checkEmail(String email){
if (StringUtils.isBlank(email)) {
return false;
}
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
public static String getFormatedValue(String valueStr, String format) {
if (StringUtils.isBlank(valueStr) || "".equals(valueStr.trim())) {
valueStr = "0";
}
DecimalFormat df = new DecimalFormat(format);
return df.format(Double.parseDouble(valueStr.trim()));
}
/**
* 对字符串采用UTF-8编码后用MD5进行摘要
*/
public static byte[] encryptMD5(String data) throws IOException {
return encryptMD5(data.getBytes(CHARSET_NAME));
}
/**
* 对字节流进行MD5摘要
*/
public static byte[] encryptMD5(byte[] data) throws IOException {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
bytes = md.digest(data);
} catch (GeneralSecurityException gse) {
throw new IOException(gse.toString());
}
return bytes;
}
/**
* 把字节流转换为十六进制表示方式
*/
public static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
/**
* 将字符型的日期转成long
*/
public static long date2Long(String date,String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
long tsvalue = 0;
try {
Timestamp ts = new Timestamp(dateFormat.parse(date).getTime());
tsvalue = ts.getTime() / 1000;
} catch (Exception e) {
return 0;
}
return tsvalue;
}
/**
* 字符型日期是否合法
* @param date
* @param format
* @return
* @author 谢旭林
* @version 创建时间2020年4月8日 下午4:23:47
*
*/
public static boolean validDateFormat(String date,String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
try {
dateFormat.parse(date);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 将字符串转译以免xml报错
*/
public static String escape4Xml(String xmlStr) {
return xmlStr.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("'", "&apos;").replace("\"", "&quot;");
}
public static List<String> extractMessageByRegular(String msg){
return extractMessageByRegular(msg,"3");
}
/**
*正则表达式匹配以##{}[]为标记的变量
* @param msg
* @return
*/
public static List<String> extractMessageByRegular(String msg,String type){
String pattern = "";
switch (type){
case "1":
pattern = "(#[^#]*#)";//##为标记
break;
case "2":
pattern = "(\\[[^\\]]*\\])"; //[]为标记
break;
case "3":
pattern = "(\\{[^\\}]*\\})";//{}为标记
break;
default:
pattern = "(\\{[^\\}]*\\})";//{}为标记
}
List<String> list=new ArrayList<String>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(msg);
while(m.find()){
list.add(m.group().substring(1, m.group().length()-1));
}
return list;
}
public static String fillValueInMsg(String msg,String variableName,String value){
return fillValueInMsg( msg, variableName, value,"3");
}
/**
* 填充msg中以##{}[]为标记的变量
* @param msg
* @param variableName
* @param value
* @param type
* @return
*/
public static String fillValueInMsg(String msg,String variableName,String value,String type){
String newValue = "";
switch (type){
case "1":
newValue = "#"+variableName+"#";//##为标记
break;
case "2":
newValue = "\\["+variableName+"\\]"; //[]为标记
break;
case "3":
newValue = "\\{"+variableName+"\\}";//{}为标记
break;
default:
newValue = "\\{"+variableName+"\\}";//{}为标记
}
if(StringUtils.isBlank(value)){
value = "";
}
return msg.replaceAll(newValue,value);
}
}

View File

@ -0,0 +1,393 @@
package com.centricsoftware.commons.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* 解压Zip文件工具类
* 同类方法{@link cn.hutool.core.util.ZipUtil}
* @author harry liang
*
*/
@Slf4j
public class ZIPUtil {
private static final int buffer = 2048;
/**
* 解压Zip文件
*
* @param path
* 文件目录
* @return 解压缩文件目录
*/
public static String unZip(String path) {
int count = -1;
String savepath = "";
File file = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
savepath = path.substring(0, path.lastIndexOf(".")) + File.separator; // 保存解压文件目录
new File(savepath).mkdir(); // 创建保存目录
ZipFile zipFile = null;
try {
try {
// zipFile = new ZipFile(path, Charset.forName("gbk"));
zipFile = new ZipFile(path, Charset.forName("utf-8")); // 解决中文乱码问题
} catch (Exception e) {
}
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
byte[] buf = new byte[buffer];
ZipEntry entry = (ZipEntry) entries.nextElement();
String filename = entry.getName();
boolean ismkdir = false;
if (filename.lastIndexOf("/") != -1) { // 检查此文件是否带有文件夹
ismkdir = true;
}
filename = savepath + filename;
if (entry.isDirectory()) { // 如果是文件夹先创建
file = new File(filename);
file.mkdirs();
continue;
}
file = new File(filename);
if (!file.exists()) { // 如果是目录先创建
if (ismkdir) {
new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs(); // 目录先创建
}
}
file.createNewFile(); // 创建文件
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
bos.flush();
bos.close();
fos.close();
is.close();
}
zipFile.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return savepath;
}
private static final int BUFFER_SIZE = 2 * 1024;
/**
*
* 压缩成ZIP 方法1
*
* @param srcDir
* 压缩文件夹路径
*
* @param out
* 压缩文件输出流
*
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
*
* false:所有文件跑到压缩包根目录下(注意不保留目录结构可能会出现同名文件,会压缩失败)
*
* @throws RuntimeException
* 压缩失败会抛出运行时异常
*
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* 压缩成ZIP 方法2
*
* @param srcFiles
* 需要压缩的文件列表
*
* @param out
* 压缩文件输出流
*
* @throws RuntimeException
* 压缩失败会抛出运行时异常
*
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
log.error("ZIP", e);
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* 递归压缩方法
*
* @param sourceFile
* 源文件
*
* @param zos
* zip输出流
*
* @param name
* 压缩后的名称
*
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
*
* false:所有文件跑到压缩包根目录下(注意不保留目录结构可能会出现同名文件,会压缩失败)
*
* @throws Exception
*
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
public static void main(String[] args) throws Exception {
/** 测试压缩方法1 */
FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));
ZIPUtil.toZip("D:/log", fos1, true);
/** 测试压缩方法2 */
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
ZIPUtil.toZip(fileList, fos2);
}
/*
* public static void main(String[] args) { unZip("F:\\110000002.zip"); String f = "F:\\110000002"; File file = new
* File(f); String[] test=file.list(); for(int i=0;i<test.length;i++){ System.out.println(test[i]); }
*
* System.out.println("------------------");
*
* String fileName = "";
*
* File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) {
* System.out.println("文 件:"+tempList[i]);
*
* fileName = tempList[i].getName();
*
* System.out.println("文件名:"+fileName); } if (tempList[i].isDirectory()) { System.out.println("文件夹:"+tempList[i]); }
* } }
*/
}

View File

@ -0,0 +1,12 @@
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

31
config/.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
config/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

94
config/pom.xml Normal file
View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.centricsoftware</groupId>
<artifactId>plmservice</artifactId>
<version>2.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>config</artifactId>
<version>2.0</version>
<name>config</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<jasypt.version>3.0.2</jasypt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--hutool集成工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.github.ulisesbocchio</groupId>-->
<!-- <artifactId>jasypt-spring-boot-starter</artifactId>-->
<!-- <version>${jasypt.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<!-- true 打包时候变量替换 -->
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<!-- <excludes>-->
<!-- <exclude>**/*.yml</exclude>-->
<!-- </excludes>-->
<includes>
<include>**/*.yml</include>
<include>logback-spring.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!-- <resource>-->
<!-- <directory>src/main/resources</directory>-->
<!-- <includes>-->
<!-- <include>application-pro.yml</include>-->
<!-- <include>application-redis.yml</include>-->
<!-- <include>application-rabbitmq.yml</include>-->
<!-- <include>application-mybatis.yml</include>-->
<!-- <include>application-plm.yml</include>-->
<!-- <include>application-center.yml</include>-->
<!-- <include>application-custom.yml</include>-->
<!-- <include>logback-spring.xml</include>-->
<!-- </includes>-->
<!-- <filtering>true</filtering>-->
<!-- </resource>-->
</resources>
</build>
</project>

View File

@ -0,0 +1,48 @@
package com.centricsoftware.config.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ExecutorConfig {
@Value("${pool.executor.corePoolSize:8}")
private int corePoolSize;
@Value("${pool.executor.maxPoolSize:8}")
private int maxPoolSize;
@Value("${pool.executor.queueCapacity:1000}")
private int queueCapacity;
@Value("${pool.executor.keepAliveTime:300}")
private int keepAliveTime;
//线程池命名
public static final String THREAD_POOL_NAME = "taskExecutorI";
@Bean(THREAD_POOL_NAME)
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(corePoolSize);
//配置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("thread-");
//配置线程空闲后的最大存活时间
executor.setKeepAliveSeconds(keepAliveTime);
// rejection-policy当pool已经达到max size的时候如何处理新任务
// CALLER_RUNS不在新线程中执行任务而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//执行初始化
executor.initialize();
return executor;
}
}

View File

@ -0,0 +1,151 @@
package com.centricsoftware.config.cons;
/**
* 系统内相关常量,公共常量放这里使用接口
* @author zheng.gong
* @date 2020/4/17
*/
public interface Constants {
/**
* 分页最大单次限制
*/
public static final int PAGE_MAX_LIMIT = 500;
/**
* 表名
* @author zheng.gong
* @date 2020/4/17
*/
interface PlmTable {
String PLM_SAMPLE="plm_sample";
}
interface Bool{
String TRUE="true";
String FALSE="false";
}
interface SysStr{
String SESSION_EXPIRE_ERROR_MSG="The client session has expired or is invalid";
String SECRET="pvKMVgcoYEtwnmqmWhJmaA==";
String AUTH_CONTENT = "ICICLE_INTERFACE_AUTH";
String AUTH_ENCODE = "beErF6b+D/CSC7k0TgVRNw==";
}
/**
* 标点符号
* @author zheng.gong
* @date 2020/4/17
*/
interface SysConts{
/**
* 点号
*/
String SYMBOL_DOT = ".";
/**
* 星号
*/
String SYMBOL_STAR = "*";
/**
* 邮箱符号
*/
String SYMBOL_EMAIL = "@";
}
/**
* http请求头
* @author zheng.gong
* @date 2020/4/17
*/
interface HttpHeadEncodingType{
String DEFAULT_CHARSET = "UTF-8";
String CONTENT_TYPE_JSON="application/json;charset=UTF-8";
String CONTENT_TYPE_XML="text/xml;charset=UTF-8";
String CONTENT_TYPE_HTML="text/html;charset=utf-8";
String CONTENT_TYPE_FORM="application/x-www-form-urlencoded";
}
/**
* redis相关常量
*/
interface Redis{
/**
* 默认配置刷新时间 7天
*/
Integer DEFUALT_PROPERTIES_RELOAD = 604800;
Integer C8INTERFACE_EXPIRE_TIME=3000;
}
/**
* rabbit相关常量
* 此类为service使用配置
*/
interface RabbitConsts {
/**
* 直接模式1
*/
String DIRECT_MODE_QUEUE_ONE = "queue.direct.1";
/**
* 队列2
*/
String QUEUE_TWO = "queue.2";
/**
* 队列3
*/
String QUEUE_THREE = "3.queue";
/**
* 分列模式
*/
String FANOUT_MODE_QUEUE = "fanout.mode";
/**
* 主题模式
*/
String TOPIC_MODE_QUEUE = "topic.mode";
/**
* 路由1
*/
String TOPIC_ROUTING_KEY_ONE = "queue.#";
/**
* 路由2
*/
String TOPIC_ROUTING_KEY_TWO = "*.queue";
/**
* 路由3
*/
String TOPIC_ROUTING_KEY_THREE = "3.queue";
/**
* 延迟队列
*/
String DELAY_QUEUE = "delay.queue";
/**
* 延迟队列交换器
*/
String DELAY_MODE_QUEUE = "delay.mode";
}
}

View File

@ -0,0 +1,36 @@
package com.centricsoftware.config.entity;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import java.sql.Struct;
import java.util.Map;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "cs.center")
public class CenterProperties {
Map<String, String> prop;
public String getValue(String key, String defValue){
String value = this.getProp().get(key);
if(StrUtil.isBlank(value)&&StrUtil.isNotBlank(defValue)){
return defValue;
}else{
return value;
}
}
public String getValue(String key){
return this.getProp().get(key);
}
}

View File

@ -0,0 +1,60 @@
package com.centricsoftware.config.entity;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.Map;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "cs")
public class CsProperties {
Map<String,String> plm;
private Environment env;
@Autowired
public CsProperties(Environment env) {
this.env = env;
}
public String getValue(String key, String defValue){
String value = this.getPlm().get(key);
if(StrUtil.isBlank(value)&&StrUtil.isNotBlank(defValue)){
return defValue;
}else{
// if(StrUtil.equals(env.getProperty("password.encrypt"),"true")){
// // 密钥
// byte[] encryptkey = Base64.decode(Constants.SysStr.SECRET);
// AES aes = SecureUtil.aes(encryptkey);
// // 解密
// return aes.decryptStr(value, CharsetUtil.CHARSET_UTF_8);
// }
return value;
}
}
public String getValue(String key){
return this.getPlm().get(key);
}
public String getProperty(String key){
return this.getEnv().getProperty(key);
}
public String getProperty(String key, String defValue){
String value = this.getEnv().getProperty(key);
if(StrUtil.isBlank(value)) {
value = defValue;
}
return value;
}
}

View File

@ -0,0 +1,27 @@
package com.centricsoftware.config.entity;
import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "es")
@Data
public class EsProperties {
private boolean enable;
private String brand;
private String scheme = "http";
/**
* ip:port以逗号分隔
*/
private String host;
private String user;
private String password;
/**
* 日志索引名
*/
private String logIndex;
}

View File

@ -0,0 +1,17 @@
#######################公共配置###################
cs.plm.common:
log:
feign:
#feign日志中响应报文中标记请求处理状态的字段支持getByPath
success-field: code
#feign日志中响应报文中标记请求处理成功的值;可以通过feign的c8_code
success-value: 0,200
#feign日志中请求报文中标记主键的字段支持getByPath
key-field: url,id,URL,ID
cs.plm:
#是否记录日志此配置用于开启ES和DB的日志记录方式
feign-log: true
#用于配置日志的存储方式
log-save-type: db # db or es

View File

@ -0,0 +1,38 @@
###这个yml文件存放es相关配置无业务
################################开发环境################################
spring:
profiles: dev
es:
enable: true
brand: PLM
host: 127.0.0.1:9200
user: elastic
password: c8admin
logIndex: plm-log-stream
---
################################测试环境################################
spring:
profiles: test
es:
enable: true
brand: PLM
host: 127.0.0.1:9200
user: elastic
password: c8admin
---
################################正式环境################################
spring:
profiles: prod
es:
enable: true
brand: PLM
host: 127.0.0.1:9200
user: elastic
password: c8admin

View File

@ -0,0 +1,31 @@
#######################导入配置###################
cs.excel.upload:
##69码导入
SKUImport:
nodeType: SKU
create: false
searchXml: <Node Parameter="Type" Op="EQ" Value="SKU" /><Attribute Id="C8_SKU_URL" Op="EQ" SValue="{C8_SKU_URL}" />
seadEmail: false
tips: "系统中找不到对应的SKU名称:{C8_SKU_URL}</br>"
isSingleSave: true
columns:
- attributeId: "C8_SKU_URL"
colName: SKU名称
update: false
required: true
tips: "不存在SKU信息</br>"
- attributeId: "C8_SKU_69Code"
colName: 69码
required: true
valid: ^\d{13}$
tips: "SKU名称为 {C8_SKU_URL} 的69码不是13位纯数字! </br>"
continueTrans: true
- attributeId: "C8_SKU_69Code"
colName: 69码
required: true
valid: <Node Parameter="Type" Op="EQ" Value="SKU" /><Attribute Id="C8_SKU_69Code" Op="EQ" SValue="{C8_SKU_69Code old}" />
validResultRequired: false
update: false
path: "Child:xx"
tips: "SKU名称为 {C8_SKU_URL} 的69码不唯一!</br>"
type: ref

View File

@ -0,0 +1,63 @@
#######################第三方企业APP配置###################
################################开发环境################################
spring:
profiles: dev
#企业微信
cs:
wechat:
url: https://qyapi.weixin.qq.com/cgi-bin
agentid: 1000999
appkey: ww0215d6203xxxxx
secret: FughJHJeTAgdF426IGRvEfeyzgGG1s6XXXXXXX
flybook:
baseUrl: https://open.feishu.cn/open-apis/
appid: cli_a19177fb9178500d
secret: uppAX8hRAS73JafIRCFHu7vUssAnynMB
dingtalk:
appkey:
secret:
agentid:
---
################################测试环境################################
spring:
profiles: test
#企业微信
cs:
wechat:
url: https://qyapi.weixin.qq.com/cgi-bin
agentid: 1000999
appkey: ww0215d6203xxxxx
secret: FughJHJeTAgdF426IGRvEfeyzgGG1s6XXXXXXX
flybook:
baseUrl: https://open.feishu.cn/open-apis/
appid: cli_a19177fb9178500d
secret: uppAX8hRAS73JafIRCFHu7vUssAnynMB
dingtalk:
appkey:
secret:
agentid:
---
################################正式环境################################
spring:
profiles: prod
#企业微信
cs:
wechat:
url: https://qyapi.weixin.qq.com/cgi-bin
agentid: 1000999
appkey: ww0215d6203xxxxx
secret: FughJHJeTAgdF426IGRvEfeyzgGG1s6XXXXXXX
flybook:
baseUrl: https://open.feishu.cn/open-apis/
appid: cli_a19177fb9178500d
secret: uppAX8hRAS73JafIRCFHu7vUssAnynMB
dingtalk:
appkey:
secret:
agentid:

View File

@ -0,0 +1,60 @@
##################数据库配置##############
##############开发环境####################
spring:
profiles: dev
#数据库配置
datasource:
dynamic:
lazy: true
primary: c8
datasource:
c8:
url: jdbc:sqlserver://120.79.18.201:1433;DatabaseName=C8
username: csidba
password: csidba
hse:
url: jdbc:postgresql://120.79.18.201:25432/exportdb
username: CSIDBA
password: CSIDBA
---
##############测试环境####################
spring:
profiles: test
#数据库配置
datasource:
dynamic:
lazy: true
primary: c8
datasource:
c8:
url: jdbc:sqlserver://120.79.18.201:1433;DatabaseName=C8
username: csidba
password: csidba
hse:
url: jdbc:postgresql://120.79.18.201:25432/exportdb
username: CSIDBA
password: CSIDBA
---
##############正式环境####################
spring:
profiles: prod
#数据库配置
datasource:
dynamic:
lazy: true
primary: c8
datasource:
c8:
url: jdbc:sqlserver://120.79.18.201:1433;DatabaseName=C8
username: csidba
password: csidba
hse:
url: jdbc:postgresql://120.79.18.201:25432/exportdb
username: CSIDBA
password: CSIDBA

View File

@ -0,0 +1,118 @@
#######################Centric8服务器地址###################
spring:
profiles: dev
cs:
plm:
# http: http://120.79.18.201:80
http: http://119.23.55.145:80
#是否自动登陆默认自动登陆只有当值不为true或者不为空时不自动登陆
auto-login: true
enum-display-cache: true
# 是否记录Feign日志
feign-log: false
#######Centric8服务器登陆用户名/密码
###密码加密代码在com.centricsoftware.core.JavaTest中
user: Administrator
#c8admin
# pwd: centric(bvXcDZBCR1rgv6yr5T8Kn7KnKd4/C4d3)
pwd: c8admin
dbhost: http://119.23.55.145:1433
dbuser: csidba
dbpwd: csidba
dbname: C8
# dbtype: Oracle
mail:
host: testmailhost
sender: administrator
senderName: administrator
senderPwd: 123456
hse:
host: localhost
portNumber: 9200
proto: http
#定时任务配置
task:
#晚上12点中午12点执行登陆
cron: 0 0 0,12 * * ?
test: 0/5 * * * * ?
---
spring:
profiles: test
cs:
plm:
http: http://119.23.55.145.32:80
#是否自动登陆默认自动登陆只有当值不为true或者不为空时不自动登陆
auto-login: true
enum-display-cache: true
# 是否记录Feign日志
feign-log: false
#######Centric8服务器登陆用户名/密码
###密码加密代码在com.centricsoftware.core.JavaTest中
user: Administrator
#c8admin
# pwd: centric(bvXcDZBCR1rgv6yr5T8Kn7KnKd4/C4d3)
pwd: c8admin
dbhost: http://119.23.55.145.32:1433
dbuser: csidba
dbpwd: csidba
dbname: C8
# dbtype: Oracle
mail:
host: testmailhost
sender: administrator
senderName: administrator
senderPwd: 123456
hse:
host: localhost
portNumber: 9200
proto: http
#定时任务配置
task:
#晚上12点中午12点执行登陆
cron: 0 0 0,12 * * ?
test: 0/5 * * * * ?
---
spring:
profiles: prod
cs:
plm:
http: http://119.23.55.145.32:80
#是否自动登陆默认自动登陆只有当值不为true或者不为空时不自动登陆
auto-login: true
enum-display-cache: false
# 是否记录Feign日志
feign-log: false
#######Centric8服务器登陆用户名/密码
###密码加密代码在com.centricsoftware.core.JavaTest中
user: Administrator
#c8admin
# pwd: centric(bvXcDZBCR1rgv6yr5T8Kn7KnKd4/C4d3)
pwd: c8admin
dbhost: http://119.23.55.145.32:1433
dbuser: csidba
#csidba
dbpwd: csidba
dbname: C8
# dbtype: Oracle
##数据库链接 用于DBUtil
pq:
dbuser: csidba
dbpwd: csidba
dbtype: Oracle
dbhost: localhost
dbname: C8REPORT
mail:
host: testmailhost
sender: administrator
senderName: administrator
senderPwd: 123456
hse:
host: localhost
portNumber: 9200
proto: http
#定时任务配置
task:
#晚上12点中午12点执行登陆
cron: 0 0 0,12 * * ?

View File

@ -0,0 +1,94 @@
###这个yml文件存放项目环境相关配置无业务
################################开发环境################################
spring:
profiles: dev
mvc:
view:
prefix: /
suffix: .jsp
thymeleaf:
enabled: false
cache: false
check-template-location: false
web:
port: 8088
logging:
path: D:/plmservice/logs
auth:
username: c8admin
password: c8admin
inter:
fileupload:
msg:
dingding:
http:
systemCode:
token:
bds:
urlPrefix:
signKey:
platformNo:
version:
http:
#定时任务配置
task:
#每周日上午3点刷新缓存
cron: 0 0 3 ? * SUN
##加密配置
---
################################测试环境################################
spring:
profiles: test
web:
port: 8088
logging:
path: D:/plmservice/logs
inter:
fileupload:
msg:
dingding:
http:
systemCode:
token:
bds:
urlPrefix:
signKey:
platformNo:
version:
http:
#定时任务配置
task:
#每周日上午3点刷新缓存
cron: 0 0 3 ? * SUN
---
################################正式环境################################
spring:
profiles: prod
web:
port: 8088
logging:
path: C:/plmservice/logs
inter:
fileupload:
msg:
dingding:
http:
systemCode:
token:
bds:
urlPrefix:
signKey:
platformNo:
version:
http:
#定时任务配置
task:
#每周日上午3点刷新缓存
cron: 0 0 3 ? * SUN

View File

@ -0,0 +1,38 @@
###这个yml文件存放rabbitmq相关配置无业务
################################开发环境################################
spring:
profiles: dev
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
---
################################测试环境################################
spring:
profiles: test
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
---
################################正试环境################################
spring:
profiles: prod
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /

View File

@ -0,0 +1,73 @@
###这个yml文件存放redis相关配置无业务
################################开发环境################################
spring:
profiles: dev
redis:
host: localhost
# 连接超时时间记得添加单位Duration
timeout: 10000ms
# Redis默认情况下有16个分片这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
cache:
# 一般来说是不用配置的Spring Cache 会根据依赖的包自行装配
type: redis
---
################################测试环境################################
spring:
profiles: test
redis:
host: localhost
# 连接超时时间记得添加单位Duration
timeout: 10000ms
# Redis默认情况下有16个分片这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
cache:
# 一般来说是不用配置的Spring Cache 会根据依赖的包自行装配
type: redis
---
################################正式环境################################
spring:
profiles: prod
redis:
host: localhost
# 连接超时时间记得添加单位Duration
timeout: 10000ms
# Redis默认情况下有16个分片这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
cache:
# 一般来说是不用配置的Spring Cache 会根据依赖的包自行装配
type: redis

View File

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan:配置文件如果发生改变将会重新加载默认值为true -->
<configuration scan="true" scanPeriod="10 seconds">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!-- 日志文件路径 -->
<springProperty scope="context" name="LOG_HOME" source="logging.file.path" defautValue="../logs"/>
<springProperty scope="context" name="PROJECT_NAME" source="spring.application.name" defautValue="plmservice"/>
<!-- 日志的存放目录-->
<property name="FILE_NAME" value="${LOG_HOME}/${PROJECT_NAME}.log"/>
<property name="TASK_FILE_NAME" value="${LOG_HOME}/${PROJECT_NAME}-task.log"/>
<property name="FILE_NAME_PATTERN" value="${LOG_HOME}/${PROJECT_NAME}.%d{yyyyMMdd}.%i.log"/>
<property name="TASK_LOG_FILE_NAME_PATTERN" value="${LOG_HOME}/${PROJECT_NAME}-task.%d{yyyy-MM-dd}.%i.log"/>
<!-- 日志格式 -->
<property name="LOG_PATTERN"
value="[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] [%thread] %logger{96} [%line] - %msg%n"/>
<!-- 日志写入控制台 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- 日志文件 记录所有级别的日志 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<append>true</append>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
<charset>utf-8</charset>
</encoder>
<file>${FILE_NAME}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${FILE_NAME_PATTERN}</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--最多保留7天log-->
<maxHistory>7</maxHistory>
</rollingPolicy>
</appender>
<!-- 定时任务日志-->
<appender name="task_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
<append>true</append>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
<charset>utf-8</charset>
</encoder>
<file>${TASK_FILE_NAME}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${TASK_LOG_FILE_NAME_PATTERN}</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--最多保留30天log-->
<maxHistory>30</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
</appender>
<springProfile name="dev">
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</springProfile>
<springProfile name="test">
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</springProfile>
<springProfile name="pro">
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</springProfile>
</configuration>

31
core/.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
core/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

202
core/pom.xml Normal file
View File

@ -0,0 +1,202 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.centricsoftware</groupId>
<artifactId>plmservice</artifactId>
<version>2.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>core</artifactId>
<version>2.0</version>
<!-- <packaging>jar</packaging>-->
<name>core</name>
<description>Demo project for Spring Boot Dev 2</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- <dependency> -->
<!-- <groupId>de.codecentric</groupId> -->
<!-- <artifactId>spring-boot-admin-starter-client</artifactId> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-actuator</artifactId> -->
<!-- </dependency> -->
<!-- ↓↓↓jsp依赖↓↓↓ -->
<!-- <dependency>-->
<!-- <groupId>javax.servlet</groupId>-->
<!-- <artifactId>javax.servlet-api</artifactId>-->
<!-- <scope>provided</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.tomcat.embed</groupId>-->
<!-- <artifactId>tomcat-embed-jasper</artifactId>-->
<!-- <scope>provided</scope>-->
<!-- </dependency>-->
<!-- ↑↑↑jsp依赖↑↑↑ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- ↓↓↓容器部署war包需要开启↓↓↓-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>org.apache.tomcat.embed</groupId>-->
<!-- <artifactId>tomcat-embed-websocket</artifactId>-->
<!-- </exclusion>-->
<!-- <exclusion>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-tomcat</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- ↑↑↑容器部署war包需要开启↑↑↑-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--lombok简化代码-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--hutool集成工具包-->
<!-- <dependency>-->
<!-- <groupId>cn.hutool</groupId>-->
<!-- <artifactId>hutool-all</artifactId>-->
<!-- </dependency>-->
<!-- plmservice各个模块功能依赖 -->
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>config</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>commons</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>enhancement</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>sso</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.centricsoftware</groupId>-->
<!-- <artifactId>integration</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.centricsoftware</groupId>-->
<!-- <artifactId>redis</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.centricsoftware</groupId>-->
<!-- <artifactId>mybatis</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.centricsoftware</groupId>-->
<!-- <artifactId>rabbitmq</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.centricsoftware</groupId>-->
<!-- <artifactId>custom</artifactId>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>plmservice</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version> 2.5.1</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>1.0.27.RELEASE</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-maven-plugin</artifactId>
<version>1.0.27.RELEASE</version>
<executions>
<execution>
<!--在编译时下载依赖包 -->
<id>resolve</id>
<goals>
<goal>resolve</goal>
</goals>
<inherited>false</inherited>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/*.tld</include>
<include>**/*.doc</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xlsx</include>
<include>**/*.xls</include>
<include>banner.txt</include>
</includes>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.tld</exclude>
<exclude>**/*.doc</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,35 @@
package com.centricsoftware.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* 代码入口
* @author zheng.gong
* @date 2020/4/21
*/
@ComponentScan("com.centricsoftware")
@EnableScheduling
@SpringBootApplication
@EnableFeignClients(basePackages = "com.centricsoftware.*")
@EnableWebMvc
@EnableAsync
@Import(cn.hutool.extra.spring.SpringUtil.class)
public class CoreApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CoreApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(CoreApplication.class, args);
}
}

View File

@ -0,0 +1,203 @@
package com.centricsoftware.core.aspect;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.centricsoftware.commons.ant.ControllerLog;
import com.centricsoftware.commons.utils.IpUtil;
import com.centricsoftware.commons.utils.SpringContextHolder;
import com.centricsoftware.config.cons.Constants;
import com.centricsoftware.config.entity.CsProperties;
import com.centricsoftware.enhancement.dto.log.FeignLogDto;
import com.centricsoftware.enhancement.dto.log.PlmLog;
import com.centricsoftware.enhancement.modules.c8.service.es.LogElasticsearchService;
import com.centricsoftware.enhancement.service.log.AsyncLogService;
import com.centricsoftware.enhancement.service.log.impl.LogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
* AopAspect对controller和service类或者带有自定义注解的类增强减少log代码冗余
* @author ZhengGong
* @date 2020/4/16
*/
@Aspect
@Component
@Slf4j
public class AopAspect extends BaseAspect {
@Resource
private LogElasticsearchService logElasticsearchService;
@Resource
private AsyncLogService asyncLogService;
@Resource
private LogServiceImpl logService;
private ThreadLocal<PlmLog> logThreadLocal = new ThreadLocal<>();
@Pointcut(value = "(execution(* com.centricsoftware.core.controller..*(..))||@annotation(com.centricsoftware.commons.ant.ControllerLog))")
public void controllerAspect(){}
@Pointcut("execution(* com.centricsoftware.enhancement.modules.c8.feign.*.*(..))||@annotation(com.centricsoftware.commons.ant.ServiceLog)")
public void serviceAspcet(){}
/**
* 对Controller环绕增强
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("controllerAspect()")
public Object controllerAround(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("---------------------Controller方法调用开始-----------------------");
// getControllerArgsDescription(joinPoint);
//是否记录日志
CsProperties csProperties = SpringContextHolder.getBean(CsProperties.class);
Instant t1 = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
Object proceed;
if(StrUtil.equals(csProperties.getValue("feign-log"), Constants.Bool.TRUE, true)){
proceed = around(joinPoint, log);
}else{
proceed = joinPoint.proceed();
}
Instant t2 = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
Duration between = Duration.between(t1, t2);
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
log.warn("{}执行开始时间:{},结束时间:{},耗时{}ms",methodSignature.getMethod(),t1,t2,between.toMillis());
log.debug("方法{}执行成功,返回结果{}",methodSignature.getMethod().getName(),proceed);
log.info("---------------------Controller方法调用结束-----------------------");
return proceed;
}
/**
* 对Service环绕增强
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("serviceAspcet()")
public Object serviceAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed = joinPoint.proceed();
log.debug("---------------------Service方法调用 开始-----------------------");
getServiceArgsDescription(joinPoint);
Instant t1 = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
Instant t2 = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
Duration between = Duration.between(t1, t2);
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
log.debug("{}执行开始时间:{},结束时间:{},耗时{}ms",methodSignature.getMethod(),t1,t2,between.toMillis());
log.debug("方法{}执行成功,返回结果{}",methodSignature.getMethod(),proceed);
log.debug("---------------------Service方法调用 结束-----------------------");
return proceed;
}
public static void getServiceArgsDescription(JoinPoint joinPoint){
//1.获取到所有的参数值的数组
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//2.获取到方法的所有参数名称的字符串数组
String[] parameterNames = methodSignature.getParameterNames();
log.debug("---------------参数列表---------------------");
for (int i =0 ,len=parameterNames.length;i < len ;i++){
log.debug("参数名:{},参数值:{}",parameterNames[i],args[i]);
}
}
// ================日志采集=======================
@Override
protected void preHandle(ProceedingJoinPoint jp, Object reqArgs) {
MethodSignature ms = (MethodSignature) jp.getSignature();
ControllerLog controllerLog = ms.getMethod().getAnnotation(ControllerLog.class);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
PlmLog plmLog = buildPlmLog(controllerLog, request, reqArgs);
logThreadLocal.set(plmLog);
}
@Override
protected void finallyHandle(MethodSignature ms, Object result,ControllerLog controllerLog) {
PlmLog plmLog = logThreadLocal.get();
// 没有注解就不记录接口日志
if (plmLog != null) {
logElasticsearchService.buildUpdatePlmLog(plmLog, result);
}
saveLog(plmLog,controllerLog);// 最后做日志存储
logThreadLocal.remove();
}
private void saveLog(PlmLog plmLog, ControllerLog controllerLog) {
CsProperties csProperties = SpringContextHolder.getBean(CsProperties.class);
String value = csProperties.getValue("log-save-type");
if(StrUtil.equals(value, "es", true)){
logElasticsearchService.saveLog(plmLog);
}
if(StrUtil.equals(value, "db", true)){
saveLogInDB(plmLog,controllerLog);
}
}
private void saveLogInDB(PlmLog plmLog,ControllerLog controllerLog) {
FeignLogDto convert = Convert.convert(FeignLogDto.class, plmLog);
if(controllerLog.interfaceLog()){
convert.setLogType("接口日志");
}else{
convert.setLogType("操作日志");
}
convert.setUrl(plmLog.getPath());
convert.setReturnMsg(plmLog.getReturnText());
convert.setRequestId(controllerLog.requestId());
convert.setResponseId(controllerLog.responseId());
logService.saveLog(convert);
}
private PlmLog buildPlmLog(ControllerLog controllerLog, HttpServletRequest request, Object param) {
String requestBody = getRequestBody(request);
String desc = Optional.ofNullable(controllerLog).map(ControllerLog::value).orElse(StringUtils.EMPTY);
PlmLog plmLog = logElasticsearchService.newLog(request.getRequestURI(), IpUtil.getIpAddr(request), param, desc);
plmLog.setDebug(requestBody);
if (request instanceof ContentCachingRequestWrapper) {
ContentCachingRequestWrapper wrappedRequest = (ContentCachingRequestWrapper) request;
String body = new String(wrappedRequest.getContentAsByteArray());
plmLog.setDebug(body);
}
return plmLog;
}
private String getRequestBody(HttpServletRequest request) {
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
}catch (Exception e){
log.error("获取请求体失败",e);
}
return stringBuilder.toString();
}
}

View File

@ -0,0 +1,203 @@
package com.centricsoftware.core.aspect;
import com.centricsoftware.commons.ant.ControllerLog;
import com.centricsoftware.commons.dto.ResEntity;
import com.centricsoftware.commons.dto.WebResponse;
import com.centricsoftware.commons.utils.JsonUtil;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.omg.CORBA.SystemException;
import org.slf4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* 基础环绕切面处理方法
* @author liaochangjiang
* @since 2024-05-07 11:59
*/
public class BaseAspect {
public Object around(ProceedingJoinPoint jp, Logger log) {
Stopwatch stopwatch = Stopwatch.createStarted();
MethodSignature ms = (MethodSignature) jp.getSignature();
ControllerLog controllerLog = ms.getMethod().getAnnotation(ControllerLog.class);
boolean logResp = !Objects.isNull(controllerLog) && controllerLog.response();
final String signatureName = getSignatureName(controllerLog, ms);
Object result = null;
try {
Object reqArgs = getRequestArgs(jp, ms);
String argsJson = StringUtils.EMPTY;
try {
argsJson = JsonUtil.toJSONString(reqArgs, new String[]{});
log.info("{} 请求参数: {}", signatureName, argsJson);
} catch (Exception e) {
log.warn("序列化请求参数失败", e);
}
preHandle(jp, argsJson);
result = jp.proceed();
if (!logResp) {
log.info("{} 耗时: {}", signatureName, stopwatch);
}
return result;
} catch (Throwable e) {
String logPrefix = "系统";
String errorLogStr = String.format("%s异常 %s", logPrefix, signatureName);
errorLogStr += " 耗时:" + stopwatch;
if (e instanceof SystemException) {
//真实日志信息
String logText = e.getLocalizedMessage();
String message = e.getMessage();
if (StringUtils.isNotEmpty(logText)) {
message = logText;
}
errorLogStr += " logText" + message;
}
log.error(errorLogStr, e);
result = handleResponse(ms, e, log);
} finally {
stopwatch.stop();
if (logResp) {
log.info("{} 耗时: {} 返回: {}", signatureName, stopwatch, JsonUtil.toJSONString(result));
}
finallyHandle(ms, result,controllerLog);
}
return result;
}
/**
* 处理前调用
*
* @author liaochangjiang
* @since 2021-09-26 19:12:55
*/
protected void preHandle(ProceedingJoinPoint jp, Object argsJson) {
}
/**
* finally处理时调用
*
* @author liaochangjiang
* @since 2021-12-27 18:59:08
*/
protected void finallyHandle(MethodSignature ms, Object result,ControllerLog controllerLog) {
}
/**
* 获取请求参数
*
* @author liaochangjiang
* @since 2022-02-25 13:10:32
*/
private Object getRequestArgs(ProceedingJoinPoint jp, MethodSignature ms) {
Object reqArgs = new Object();
if (ArrayUtils.getLength(jp.getArgs()) >= 1 && (jp.getArgs()[0] instanceof ResEntity)) {
reqArgs = jp.getArgs()[0];
} else {
String name = ms.getMethod().getDeclaringClass().getName();
if (name.endsWith("Controller") || name.endsWith("C8Feign")) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return reqArgs;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String contentType = request.getContentType();
if (org.apache.commons.lang3.StringUtils.isNotBlank(contentType) && contentType.contains("form-")) {
Map<String, String[]> parameterMap = request.getParameterMap();
if (!parameterMap.isEmpty()) {
return parameterMap;
}
}
return request.getParameterMap();
// Object firstNormalArgs = getFirstNormalArgs(jp);
// if (firstNormalArgs == null) {
// return request.getParameterMap();
// }
// reqArgs = firstNormalArgs;
}
}
return reqArgs;
}
/**
* 获取第一个正常参数
*
* @author liaochangjiang
* @since 2022-05-07 09:20:32
*/
private Object getFirstNormalArgs(ProceedingJoinPoint jp) {
if (jp.getArgs().length == 0) {
return null;
}
Object[] args = jp.getArgs();
for (Object arg : args) {
if (!(arg instanceof ServletRequest) && !(arg instanceof ServletResponse) && !(arg instanceof HttpSession)
&& !(arg instanceof MultipartFile) && !(arg instanceof Model)) {
return arg;
}
}
return null;
}
/**
* 处理异常响应
*
* @author liaochangjiang
* @since 2021-09-26 19:03:29
*/
@SuppressWarnings("rawtypes")
protected Object handleResponse(MethodSignature ms, Throwable e,Logger log) {
Class<?> returnType = ms.getReturnType();
if (returnType == Void.TYPE) {
Optional.ofNullable(RequestContextHolder.getRequestAttributes()).map(t -> (ServletRequestAttributes) t)
.map(ServletRequestAttributes::getResponse)
.ifPresent(resp -> writeResponse(resp,WebResponse.failure(e.getMessage()),log));
return null;
}
try {
return returnType.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void writeResponse(HttpServletResponse response, ResEntity resp, Logger log) {
response.setContentType("application/json;charset=UTF-8");
try {
response.getWriter().print(JsonUtil.toJSONString(resp));
if (!resp.isSuccess()) {
response.sendError(resp.getCode(), resp.getMsg());
}
} catch (IOException e) {
log.error("响应失败", e);
}
}
protected String getSignatureName(ControllerLog controllerLog, MethodSignature ms) {
if (!Objects.isNull(controllerLog) && StringUtils.isNotBlank(controllerLog.value())) {
return controllerLog.value() + "|" + ms.toShortString();
}
return ms.toShortString();
}
}

View File

@ -0,0 +1,77 @@
package com.centricsoftware.core.config;
import cn.hutool.core.util.StrUtil;
import com.centricsoftware.commons.utils.SpringUtil;
import com.centricsoftware.config.cons.Constants;
import com.centricsoftware.config.entity.CsProperties;
import com.centricsoftware.enhancement.modules.c8.component.EnumCache;
import com.centricsoftware.enhancement.modules.c8.service.C8LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
/**
* 包含一些启动后需要注册的信息
* @author zheng.gong
* @date 2020/4/21
*/
@Slf4j
@Configuration
public class BootConfig {
/**
* 按照标准时间来算晚上12点中午12点执行登陆
*/
@Scheduled(cron = "${task.cron}")
public void job1() {
log.info("【重新登陆】"+LocalDateTime.now());
}
/**
* 启动后配置
* @return LoadingConfig
*/
@Bean
public LoadingConfig cfg(){
return new LoadingConfig();
}
/**
* 启动后的初始化操作
* @author zheng.gong
* @date 2020/4/23
*/
static class LoadingConfig{
@Autowired
CsProperties csProperties;
/**
* 启动后自动登陆PLM
*/
@PostConstruct
public void init(){
if(StrUtil.equals(csProperties.getValue("auto-login"), Constants.Bool.TRUE,true) || StrUtil.isBlank(csProperties.getValue(
"auto-login"))){
log.debug("===========系统启动后登陆PLM============");
C8LoginService loginService = SpringUtil.getBean(C8LoginService.class);
loginService.login();
log.debug("=========登陆成功!=========");
log.debug("=========开始初始化缓存!=========");
EnumCache enumCache = SpringUtil.getBean(EnumCache.class);
boolean equals = StrUtil.equals(csProperties.getValue("enum-display-cache"), Constants.Bool.TRUE, true);
enumCache.init(equals);
log.debug("=========初始化缓存成功!=========");
}else{
log.debug("===========系统启动后不登陆PLM============");
}
}
}
}

View File

@ -0,0 +1,54 @@
package com.centricsoftware.core.config;
import com.centricsoftware.enhancement.filter.AddCookieFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* 跨域处理
* @author zheng.gong
* @date 2020/4/16
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private static final long MAX_AGE_SECS = 3600;
@Resource
AddCookieFilter addCookieFilter;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.maxAge(MAX_AGE_SECS);
}
/**
* 注册拦截器
* @param registry InterceptorRegistry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(addCookieFilter)
.addPathPatterns("/**");
}
/**
* 注册拦截器
* @param registry InterceptorRegistry
*/
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(new SimpleAuthInterceptor()).addPathPatterns(interceptLIst());
// }
//
// public List<String> interceptLIst(){
// return Lists.newArrayList("/test/testAuth");
// }
}

View File

@ -0,0 +1,193 @@
package com.centricsoftware.core.controller;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.centricsoftware.commons.ant.ControllerLog;
import com.centricsoftware.commons.dto.ResEntity;
import com.centricsoftware.commons.dto.WebResponse;
import com.centricsoftware.commons.em.ResCode;
import com.centricsoftware.commons.utils.ExportExcel;
import com.centricsoftware.commons.utils.IpUtil;
import com.centricsoftware.config.entity.CenterProperties;
import com.centricsoftware.core.dto.DataPackage;
import com.centricsoftware.core.service.CommonExportService;
import com.centricsoftware.enhancement.dto.log.FeignLogDto;
import com.centricsoftware.enhancement.modules.c8.component.EnumCache;
import com.centricsoftware.enhancement.modules.c8.dto.dep.DepPath;
import com.centricsoftware.enhancement.modules.c8.service.C8NodeService;
import com.centricsoftware.enhancement.modules.dml.dto.node.change.C8OperationNode;
import com.centricsoftware.enhancement.modules.dml.dto.node.search.C8Search;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 测试控制类
* @author zheng.gong
* @date 2020/4/16
*/
@Slf4j
@RequestMapping("/test")
@Controller
public class TestController {
@Value("${cs.plm.http}")
private String host;
@Autowired
CenterProperties centerProperties;
@Autowired
C8NodeService c8NodeService;
@Resource
private CommonExportService commonExportService;
/**
* jsp测试
*
* @return
*/
@RequestMapping("/hello")
@ResponseBody
@ControllerLog("日志采集")
public ResEntity hello() {
// String name = c8NodeService.queryExpressionResult("`Node Name`", "centric://REFLECTION/INSTANCE/User/Administrator");
return WebResponse.success("欢迎你:"+"; host:"+host);
}
/**
* jsp测试
* @return
*/
@RequestMapping("/testJsp")
public String testJsp(){
return "index";
}
@ResponseBody
@PostMapping("/testParam")
public ResEntity testDemo(@RequestBody Map<Object,Object> map){
log.debug("get json param:{}", JSONUtil.toJsonStr(map));
Assert.isTrue(map.containsKey("test"),"不包含test");
return WebResponse.success(ResCode.SUCCESS,map);
}
@ResponseBody
@PostMapping("/testProp")
public ResEntity testCsProp(){
Map<String, String> plm = centerProperties.getProp();
return WebResponse.success(ResCode.SUCCESS,plm);
}
@ResponseBody
@PostMapping("testCookie")
public ResEntity testCookie() throws Exception {
return WebResponse.success(ResCode.SUCCESS);
}
@ResponseBody
@PostMapping("logout")
public ResEntity logout() throws Exception {
return WebResponse.success(ResCode.SUCCESS);
}
@RequestMapping("/testXML")
@ResponseBody
@ControllerLog("执行XML日志")
public ResEntity cookie() {
String xml = C8OperationNode.changeNode("C1402").changeAttribute("Code", "string", "10086").getXml();
String url = c8NodeService.createURL();
// String materialSecurityGroup1 = C8OperationNode.createNode(url, "MaterialSecurityGroup").getXml();
c8NodeService.processNode(xml);
return WebResponse.success(xml);
}
@Resource
EnumCache enumCache;
@ResponseBody
@RequestMapping("testEnum")
public ResEntity testEnum() throws Exception {
String fullnameByDisplay = enumCache.getFullnameByDisplay("C8_Apeed", "选中");
return WebResponse.success(ResCode.SUCCESS,fullnameByDisplay);
}
@ResponseBody
@RequestMapping("/getIP")
public ResEntity getIp(HttpServletRequest request) throws Exception {
String ip = IpUtil.getIpAddr(request);
return WebResponse.success(ResCode.SUCCESS,ip);
}
@ResponseBody
@RequestMapping("/excel")
public ResEntity excel(MultipartFile file) throws Exception {
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
List<Map<String, Object>> maps = reader.readAll();
System.out.println(maps.toString());
return WebResponse.success(ResCode.SUCCESS);
}
/**
* Excel导出通用方式
* @author liaochangjiang
* @since 2024-03-05 14:22
*/
@PostMapping("exportExcel")
public void export1(HttpServletResponse response) throws Exception {
// final ExportExcel excel = commonExportService.export1();
// excel.write(response, "区域块化导出.xlsx").dispose();
// commonExportService.export2(response);// 固定模板填充占位
// commonExportService.export5(response);// 固定模板填充占位
// final ExportExcel excel = commonExportService.export3(response);// Launchmap实现
// excel.write(response, "Launchmap实现.xlsx").dispose();
// commonExportService.export4(response);// 动态table填充占位
}
@ResponseBody
@RequestMapping("/test")
@ControllerLog(value = "测试日志",interfaceLog = true)
public ResEntity testLog(String name,String url,HttpServletResponse response){
return WebResponse.success(ResCode.SUCCESS);
}
@ResponseBody
@RequestMapping("/test1")
@ControllerLog(value = "测试日志1",interfaceLog = true)
public ResEntity testLog1(@RequestBody FeignLogDto dto){
return WebResponse.success(ResCode.SUCCESS);
}
@ResponseBody
@RequestMapping("/test2")
public ResEntity test(){
String xml = C8Search.newSearch("DataPackage")
.attr("C8_DP_Type", "EQ", "C8_DPType:1")
.attr("C8_DP_CloComState", "EQ", "true")
.attrRef("Category1", "EQ", "C1848462", "Child:__Parent__")
.getXml();
DepPath depPath = DepPath.builderXml()
.xml(xml)
.build();
List<DataPackage> dataPackages = c8NodeService.depPathByEntity(depPath, DataPackage.class);
return WebResponse.success(ResCode.SUCCESS);
}
}

View File

@ -0,0 +1,13 @@
package com.centricsoftware.core.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
@Data
public class BaseDto implements Serializable {
@JsonIgnore
private String url;
}

View File

@ -0,0 +1,35 @@
package com.centricsoftware.core.dto;
import com.centricsoftware.enhancement.modules.c8.ant.DepPathField;
import com.centricsoftware.enhancement.modules.c8.em.DepPathEntityType;
import com.centricsoftware.enhancement.util.ExportUtil.ExportTemplateRegion;
import lombok.Data;
import java.io.InputStream;
@Data
@ExportTemplateRegion(row1 = 0, col1 = 2, row2 = 11, col2 = 3, groups = "akaBuyTags")
@ExportTemplateRegion(row1 = 3, col1 = 1, row2 = 9, col2 = 1, groups = "launchmap")
public class CommonExportDto {
private InputStream styleImageIn;
private InputStream styleImageIn1;
private Integer index;
// 名称
@DepPathField(exp = "$Name")
private String name;
// 编码
@DepPathField(exp = "Code")
private String code;
// 描述
@DepPathField(exp = "Description")
private String description;
// 图片
@DepPathField(exp = "Images[].Viewable")
private String realImgUrl;
}

View File

@ -0,0 +1,32 @@
package com.centricsoftware.core.dto;
import com.centricsoftware.enhancement.modules.c8.ant.DepPathField;
import com.centricsoftware.enhancement.modules.c8.em.DepPathEntityType;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Data
public class DataPackage {
/**
* 唯一id
*/
@DepPathField(exp = "$URL")
private String url;
@DepPathField(exp = "C8_DP_AcceptTechPack")
private boolean acceptTechPack;
@DepPathField(exp = "C8_DP_BOM", type = DepPathEntityType.DOUBLE)
private Double bom;
@DepPathField(exp = "C8_DP_DesignType")
private String designType;
@DepPathField(exp = "C8_DP_DesignType", type = DepPathEntityType.ENUM_DESC)
private String designTypeDesc;
@DepPathField(exp = "C8_DP_DesignType", type = DepPathEntityType.ENUM_VALUE)
private String designTypeValue;
@DepPathField(exp = "C8_DP_DesignActualDate", type = DepPathEntityType.DATA)
private Date designActualDate;
}

View File

@ -0,0 +1,122 @@
package com.centricsoftware.core.handler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.centricsoftware.commons.dto.ResEntity;
import com.centricsoftware.commons.dto.WebResponse;
import com.centricsoftware.commons.em.ResCode;
import com.centricsoftware.commons.exception.BaseException;
import com.centricsoftware.commons.exception.ParamException;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.validation.ConstraintViolationException;
/**
* 全局异常处理
* @author ZhengGong
* @date 2019/5/24
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = NoHandlerFoundException.class)
public ResEntity handleNoHandlerFoundException(NoHandlerFoundException e) {
log.info("-------------------------进入全局异常捕获NoHandlerFoundException---------------------------");
log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", e.getRequestURL(), e.getHttpMethod());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.REQUEST_NOT_FOUND);
}
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public ResEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
log.info("-------------------------进入全局异常捕获HttpRequestMethodNotSupportedException---------------------------");
log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", e.getMethod(), JSONUtil.toJsonStr(e.getSupportedHttpMethods()));
log.error("异常栈:",e);
return WebResponse.failure(ResCode.HTTP_BAD_METHOD);
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.info("-------------------------进入全局异常捕获MethodArgumentNotValidException---------------------------");
log.error("【全局异常拦截】MethodArgumentNotValidException", e);
log.error("异常栈:",e);
return WebResponse.failure(ResCode.BAD_REQUEST.getCode(), e.getBindingResult()
.getAllErrors()
.get(0)
.getDefaultMessage(), false);
}
@ExceptionHandler(value = ConstraintViolationException.class)
public ResEntity handleConstraintViolationException(ConstraintViolationException e) {
log.info("-------------------------进入全局异常捕获ConstraintViolationException---------------------------");
log.error("【全局异常拦截】ConstraintViolationException", e);
log.error("异常栈:",e);
return WebResponse.failure(ResCode.BAD_REQUEST.getCode(), CollUtil.getFirst(e.getConstraintViolations())
.getMessage(), null);
}
@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
public ResEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
log.info("-------------------------进入全局异常捕获MethodArgumentTypeMismatchException---------------------------");
log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", e.getName(), e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.PARAM_NOT_MATCH);
}
@ExceptionHandler(value = HttpMessageNotReadableException.class)
public ResEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.info("-------------------------进入全局异常捕获HttpMessageNotReadableException---------------------------");
log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.PARAM_NOT_NULL);
}
@ExceptionHandler(value = MissingServletRequestParameterException.class)
public ResEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
log.info("-------------------------进入全局异常捕获MissingServletRequestParameterException---------------------------");
log.error("【全局异常拦截】MissingServletRequestParameterException: 异常信息 {}", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.PARAM_NOT_MATCH,e.getMessage());
}
@ExceptionHandler(value = ParamException.class)
public ResEntity handleParamException(ParamException e) {
log.info("-------------------------进入全局异常捕获ParamException---------------------------");
log.error("【全局异常拦截】ParamException: 异常信息 {}", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.PARAM_NOT_NULL,e.getMessage());
}
@ExceptionHandler(value = JsonProcessingException.class)
public ResEntity handleJsonProcessingException(JsonProcessingException e) {
log.info("-------------------------进入全局异常捕获JsonProcessingException---------------------------");
log.error("【全局异常拦截】JsonProcessingException: 异常信息 {}", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.JSON_PARSE_ERROR,e.getMessage());
}
@ExceptionHandler(value = BaseException.class)
public ResEntity handleBaseException(BaseException e) {
log.error("【全局异常拦截】BaseException: 异常信息 {}", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.parse(e.getCode()),e.getMessage());
}
@ExceptionHandler(value = Exception.class)
public ResEntity handleGlobalException(Exception e) {
log.info("-------------------------进入全局异常捕获Exception---------------------------");
log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.SYSTEM_RUNTIME_ERROR,e.getMessage());
}
@ExceptionHandler(value = IllegalArgumentException.class)
public ResEntity handleAssertException(IllegalArgumentException e){
log.info("-------------------------进入全局异常捕获Exception---------------------------");
log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
log.error("异常栈:",e);
return WebResponse.failure(ResCode.SYSTEM_RUNTIME_ERROR,e.getMessage());
}
}

View File

@ -0,0 +1,216 @@
package com.centricsoftware.core.service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.centricsoftware.commons.utils.ExportExcel;
import com.centricsoftware.commons.utils.MarkImageUtil;
import com.centricsoftware.core.dto.CommonExportDto;
import com.centricsoftware.enhancement.modules.c8.component.design.chain.IDepPathSearchChain;
import com.centricsoftware.enhancement.modules.c8.dto.dep.DepPath;
import com.centricsoftware.enhancement.modules.c8.service.C8NodeService;
import com.centricsoftware.enhancement.util.ExportUtil.AnalysisCell;
import com.centricsoftware.enhancement.util.ExportUtil.ExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Service
public class CommonExportService {
@Resource
private ExportUtil exportUtil;
@Resource
private C8NodeService c8NodeService;
@Resource
private IDepPathSearchChain iDepPathSearchChain;
// 本地资源类路径
private static final String classPath = "D:/plmservice/";
private List<CommonExportDto> getBoList () {
List<String> list = Lists.newArrayList();
list.add("C482");
list.add("C1402");
list.add("C1403");
list.add("C523");
list.add("C525");
DepPath deppath = DepPath.builder().addUrls(list).build();
List<CommonExportDto> resultList = iDepPathSearchChain.execute(deppath,CommonExportDto.class,null);
for (CommonExportDto bo : resultList) {
bo.setStyleImageIn(c8NodeService.getFileFromDirectAddr(bo.getRealImgUrl()));
}
return resultList;
}
public ExportExcel export1() throws Exception {
// 获取配色信息
List<CommonExportDto> list = getBoList();
ClassPathResource classPathResource = new ClassPathResource("template/export1.xlsx");
try (InputStream in = classPathResource.getInputStream()) {
XSSFWorkbook wb = new XSSFWorkbook(Objects.requireNonNull(in));
ExportExcel excel = new ExportExcel(wb, wb.getSheetAt(0));
exportUtil.initTemplateRegion(CommonExportDto.class, "akaBuyTags");
XSSFSheet sheet = excel.getSrcWb().cloneSheet(0, "sheet1");
excel.setSheet(sheet);
exportUtil.fillDataComment(excel,7,list);
sheet.getPrintSetup().setScale((short) 75);
sheet.getPrintSetup().setTopMargin(0);
wb.removeSheetAt(0);
return excel;
} finally {
exportUtil.remoteTemplateRegion();
}
}
/**
* 获取数据
* @author liaochangjiang
* @since 2024-03-05 15:04
*/
private CommonExportDto getData () {
// 获取配色信息
CommonExportDto bo = getBoList().get(0);
// 获取到的BO进行图片填充
bo.setStyleImageIn(c8NodeService.getFileFromDirectAddr(bo.getRealImgUrl()));
bo.setStyleImageIn1(c8NodeService.getImageViewable("C1616"));
return bo;
}
/**
* 固定模板导出
* @author liaochangjiang
* @since 2024-03-05 15:01
*/
public void export2(HttpServletResponse response) throws Exception {
ExportUtil.setExportResponseInfo(response, "固定模板导出.xlsx");// 设置文件名
CommonExportDto bo = getData();
String template = "template/export2.xlsx";// 获取模板文件
exportUtil.exportByStatic(response.getOutputStream(),template,bo);// 固定模板导出
}
/**
* 固定模板导出-多数据源
* @author liaochangjiang
* @since 2024-03-05 15:01
*/
public void export5(HttpServletResponse response) throws Exception {
ExportUtil.setExportResponseInfo(response, "固定模板导出-多数据源.xlsx");// 设置文件名
CommonExportDto bo = getData();
// 获取配色信息
List<CommonExportDto> list = getBoList();
List<Object> request = Lists.newArrayList();
request.add(new FillWrapper("list", list));
request.add(bo);
String template = "template/export5.xlsx";// 获取模板文件
exportUtil.exportByStatic(response.getOutputStream(),template,request);// 固定模板导出
}
/**
* 做图片转换-打上星号或者文字
* @author liaochangjiang
* @since 2024-02-20 21:05
*/
public InputStream exchangeImage(InputStream sourceIn) throws Exception {
Map<String, BufferedImage> imageMap = getImageIcon();
if (sourceIn == null) {
return null;
}
// 获取初始的图片的宽度
Image img = ImageIO.read(sourceIn);
// 宽度
int initX = img.getWidth(null);
// 高度
int initY = img.getHeight(null);
int iconWidth = 50;
int x = 0;
int y = 0;
// 添加对应的图标坐标
return MarkImageUtil.addImgMark(imageMap.get("red"),iconWidth,iconWidth, img,x,y,initX,initY);
}
/**
* 插入文字
* @return
*/
public InputStream addTextMark(InputStream sourceIn) throws IOException {
if (sourceIn == null) {
return null;
}
// 获取初始的图片的宽度
Image img = ImageIO.read(sourceIn);
// 宽度
int initX = img.getWidth(null);
// 高度
int initY = img.getHeight(null);
Color color = Color.RED;
Font font = new Font("微软雅黑", Font.BOLD, 18);
return MarkImageUtil.addTextMark(img, 10, 10, initX, initY, "测试文字", color, font);
}
/**
* 获取图片的流集合用于打星
* @author liaochangjiang
* @since 2024-02-20 21:04
*/
public Map<String,BufferedImage> getImageIcon() throws Exception {
Map<String,BufferedImage> imageMap = new HashMap<>();
imageMap.put("red", ImageIO.read(Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("static/icon/red.jpg"))));// 核心款
return imageMap;
}
public ExportExcel export3(HttpServletResponse response) throws Exception {
// 获取配色信息
List<CommonExportDto> list = getBoList();
ClassPathResource classPathResource = new ClassPathResource("template/export3.xlsx");
try (InputStream in = classPathResource.getInputStream()) {
XSSFWorkbook wb = new XSSFWorkbook(Objects.requireNonNull(in));
ExportExcel excel = new ExportExcel(wb, wb.getSheetAt(0));
exportUtil.initTemplateRegion(CommonExportDto.class, "launchmap");
XSSFSheet sheet = excel.getSrcWb().cloneSheet(0, "sheet1");
excel.setSheet(sheet);
exportUtil.fillDataComment(excel,32,list);
sheet.getPrintSetup().setScale((short) 75);
sheet.getPrintSetup().setTopMargin(0);
wb.removeSheetAt(0);
return excel;
} finally {
exportUtil.remoteTemplateRegion();
}
}
public void export4(HttpServletResponse response) throws Exception {
ExportUtil.setExportResponseInfo(response, "列表型导出.xlsx");// 设置文件名
String template = "template/export4.xlsx";// 获取模板文件
// 获取数据
List<CommonExportDto> list = getBoList();
for (int i = 0; i < list.size(); i++) {
list.get(i).setIndex(i + 1);
}
exportUtil.exportByStatic(response.getOutputStream(),template,list);// 固定模板导出
}
}

View File

@ -0,0 +1,39 @@
package com.centricsoftware.core.task.config;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
/**
* 使用java配置文件配置task
*
* @author zheng.gong
* @date 2020/4/21
*/
@Configuration
@EnableScheduling
@ComponentScan(basePackages = {"com.centricsoftware.core.task.job"})
public class TaskConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
/**
* 这里等同于配置文件配置
* {@code spring.task.scheduling.pool.size=20} - Maximum allowed number of threads.
* {@code spring.task.scheduling.thread-name-prefix=Job-Thread- } - Prefix to use for the names of newly created threads.
* {@link org.springframework.boot.autoconfigure.task.TaskSchedulingProperties}
*/
@Bean
public Executor taskExecutor() {
return new ScheduledThreadPoolExecutor(20, new BasicThreadFactory.Builder().namingPattern("Job-Thread-%d").build());
}
}

View File

@ -0,0 +1,38 @@
package com.centricsoftware.task.job.inter;
import cn.hutool.core.util.StrUtil;
import com.centricsoftware.config.cons.Constants;
import com.centricsoftware.enhancement.service.log.impl.LogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 删除接口日志操作日志等
*/
@Component
@Slf4j
public class DeleteLogTask {
@Resource
LogServiceImpl logService;
//注入cs.plm.feign-log的yml配置
@Value("${cs.plm.feign-log:false}")
private String feignLog;
@Scheduled(cron = "0 0 5 * * ? ") //每天凌晨5点
public void deleteLog() {
log.info("删除日志开始..");
if(StrUtil.equals(feignLog, Constants.Bool.TRUE, true)){
int count = logService.deleteLog(60);
log.info("删除日志{}条" ,count);
}else{
log.info("未启用日志记录,不执行删除操作。启用配置项:{}" ,"cs.plm.feign-log");
}
log.info("删除日志结束");
}
}

View File

@ -0,0 +1,39 @@
###这个yml文件存放系统级别的相关配置
spring:
application:
name: plmservice
http:
encoding:
charset: UTF-8
profiles:
active: @profileActive@
include: redis,rabbitmq,mybatis,plm,import,pro,common,sso,integration,es
server:
port: ${web.port}
tomcat:
uri-encoding: UTF-8
servlet:
context-path: /plmservice
logging:
config: classpath:logback-spring.xml
file:
path: ${web.logging.path}
feign:
httpclient:
enabled: false
okhttp:
enabled: true
#最大连接数
http:
maxTotal: 100
#并发数
defaultMaxPerRoute: 20
#创建连接的最长时间
connectTimeout: 10000
#从连接池中获取到连接的最长时间
connectionRequestTimeout: 5000
#数据传输的最长时间
socketTimeout: 100000
#线程失活检查
validateAfterInactivity: 30000

View File

@ -0,0 +1,7 @@
_ _
___ ___ _ __ | |_ _ __ (_) ___
/ __|/ _ \| '_ \ | __|| '__|| | / __|
| (__| __/| | | || |_ | | | || (__
\___|\___||_| |_| \__||_| |_| \___|
https://www.centricsoftwarechina.com/about-us/
:: Spring Boot C8 base on okHttp:: (v2.2.6.RELEASE)

View File

@ -0,0 +1,26 @@
###这个yml文件存放系统级别的相关配置
spring:
application:
name: plmservice
# boot:
# admin:
# client:
# url: http://localhost:9001
logging:
file:
path: D:/plmservice/logs
#management:
# health:
# elasticsearch:
# enabled: false
# redis:
# enabled: false
# db:
# enabled: false
# endpoints:
# web:
# exposure:
# include: '*'
# endpoint:
# logfile:
# external-file: D:/plmservice/logs/plmservice.log

View File

@ -0,0 +1,8 @@
<?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
<deployment>
<exclusions>
<module name="org.slf4j" />
</exclusions>
</deployment>
</jboss-deployment-structure>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,16 @@
<%--
Created by IntelliJ IDEA.
User: zheng.gong
Date: 2020/6/17
Time: 16:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
test jsp
</body>
</html>

View File

@ -0,0 +1,16 @@
package com.centricsoftware.core.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
@Data
@Accessors(chain = true)
public class TimeSeries {
private String message;
@JsonProperty("@timestamp")
private LocalDateTime startTime;
}

View File

@ -0,0 +1,204 @@
package com.centricsoftware.core.service;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch._types.aggregations.AggregationBuilders;
import co.elastic.clients.elasticsearch._types.aggregations.StringTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import com.centricsoftware.commons.utils.JsonUtil;
import com.centricsoftware.config.entity.EsProperties;
import com.centricsoftware.core.CoreApplication;
import com.centricsoftware.core.model.TimeSeries;
import com.centricsoftware.enhancement.dto.log.PlmLog;
import com.centricsoftware.enhancement.dto.log.QueryPlmLogReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Slf4j
@SpringBootTest(classes = CoreApplication.class)
public class ElasticsearchClientTest {
@Resource
private ElasticsearchClient client;
@Resource
private EsProperties esProperties;
@Test
public void testSearch() throws IOException {
SearchResponse<TimeSeries> search = client.search(s -> s
.index(esProperties.getLogIndex())
// .query(q->q.matchAll(QueryBuilders.matchAll().build()))
.query(q -> q
.term(t -> t
.field("message")
.value(v -> v.stringValue("hell"))
)
)
,
TimeSeries.class);
for (Hit<TimeSeries> hit : search.hits().hits()) {
System.out.println(hit.source());
}
}
@Test
public void testInsert() throws IOException {
IndexRequest<TimeSeries> req = new IndexRequest.Builder<TimeSeries>()
.index(esProperties.getLogIndex())
.document(new TimeSeries().setMessage("hello").setStartTime(LocalDateTime.now()))
.build();
IndexResponse index = client.index(req);
System.out.println(JsonUtil.toJSONString(index));
}
@Test
public void testSaveLog() {
PlmLog data = new PlmLog()
.setPath("PLM测试2")
.setName("测试接口")
.setHost("127.0.0.1")
.setBrand("PLM")
.setStartTime(LocalDateTime.now())
.setEndTime(LocalDateTime.now().plusSeconds(20))
.setSuccess(true)
.setCostMs(20000L)
.setParam("[{\"printingComment\":\"\",\"TransferKey\":\"C6227096\",\"stylecode\":\"152238715\",\"phase\":\"首样\",\"supplier\":\"\",\"mechcomment\":\"\",\"replicate\":\"右袖袋减短,按样衣画线;袖长做准;\",\"CommentsComfirmDate\":\"2021-07-13 10:45:55\",\"ReType\":\"复版+复花版\",\"replicate1\":\"右袖袋减短,按样衣画线;袖长做准;\",\"replicate2\":\"\",\"replicate3\":\"\",\"issueType\":\"不提供图稿\",\"ReTypePhase\":\"复版+复花版\"}]")
.setReturnCode("0")
.setReturnMsg("操作成功")
.setReturnText("{\"Sucess\":true,\"Msg\":\"接收成功\",\"Detail\":[{\"Result\":true,\"ErrorMsg\":\"\",\"TransferKey\":\"C6227096\"}]}");
for (int i = 0;i < 10000;i++) {
data.setName("测试接口" + i);
IndexRequest<PlmLog> req = new IndexRequest.Builder<PlmLog>()
.index(esProperties.getLogIndex())
.document(data)
.build();
IndexResponse index = null;
try {
index = client.index(req);
if (log.isDebugEnabled()) {
log.debug("index: {}, id:{}, result:{}", index.index(), index.id(), index.result());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void testQueryLogs() throws IOException {
QueryPlmLogReq req = new QueryPlmLogReq();
req.setPath("ESCM.SetView_FB");
req.setName("测试接口");
req.setParam("printingComment");
SearchResponse<PlmLog> search = client.search(s -> s
.index(esProperties.getLogIndex())
.query(q -> {
BoolQuery.Builder builder = QueryBuilders.bool();
List<Query> param = new ArrayList<>();
if (StringUtils.isNotBlank(req.getPath())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("path").value(v -> v.stringValue(req.getPath())).build())
.build());
}
if (StringUtils.isNotBlank(req.getName())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("name").value(v -> v.stringValue(req.getName())).build())
.build());
}
if (StringUtils.isNotBlank(req.getBrand())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("brand").value(v -> v.stringValue(req.getBrand())).build())
.build());
}
if (StringUtils.isNotBlank(req.getStartTimeBegin())) {
param.add(new Query.Builder()
.range(QueryBuilders.range().field("@timestamp").gte(JsonData.of(req.getStartTimeBegin())).build())
.build());
}
if (StringUtils.isNotBlank(req.getStartTimeEnd())) {
param.add(new Query.Builder()
.range(QueryBuilders.range().field("@timestamp").lt(JsonData.of(req.getStartTimeEnd())).build())
.build());
}
if (StringUtils.isNotBlank(req.getEndTimeBegin())) {
param.add(new Query.Builder()
.range(QueryBuilders.range().field("endTime").gte(JsonData.of(req.getEndTimeBegin())).build())
.build());
}
if (StringUtils.isNotBlank(req.getEndTimeEnd())) {
param.add(new Query.Builder()
.range(QueryBuilders.range().field("endTime").lt(JsonData.of(req.getEndTimeEnd())).build())
.build());
}
if (Objects.nonNull(req.getSuccess())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("success").value(v -> v.booleanValue(req.getSuccess())).build())
.build());
}
if (StringUtils.isNotBlank(req.getHost())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("host").value(v -> v.stringValue(req.getHost())).build())
.build());
}
if (StringUtils.isNotBlank(req.getParam())) {
param.add(new Query.Builder()
.matchPhrase(QueryBuilders.matchPhrase().field("param").query(req.getParam()).build())
.build());
}
if (Objects.nonNull(req.getReturnCode())) {
param.add(new Query.Builder()
.term(QueryBuilders.term().field("returnCode").value(v -> v.longValue(req.getReturnCode())).build())
.build());
}
if (StringUtils.isNotBlank(req.getReturnText())) {
param.add(new Query.Builder()
.matchPhrase(QueryBuilders.matchPhrase().field("returnText").query(req.getReturnText()).build())
.build());
}
builder = builder.filter(param);
return q.bool(builder.build());
})
.from((int) ((req.getPageNum() - 1) * req.getPageSize().intValue()))
.size(req.getPageSize().intValue())
,
PlmLog.class);
System.out.println(JsonUtil.toJSONString(search.hits().hits().stream().map(Hit::source).collect(Collectors.toList())));
}
@Test
public void testAggs() throws IOException {
SearchResponse<PlmLog> resp = client.search(s -> s
.index(esProperties.getLogIndex())
.query(q -> q
.term(t -> t
.field("brand")
.value(v -> v.stringValue("od-clo"))
)
)
.aggregations("desc", Aggregation.of(t -> t.terms(AggregationBuilders.terms().field("name").size(100).build())))
.size(0)
, PlmLog.class);
Aggregate aggr = resp.aggregations().get("desc");
List<StringTermsBucket> array = aggr.sterms().buckets().array();
List<String> collect = array.stream().map(StringTermsBucket::key).collect(Collectors.toList());
System.out.println(JsonUtil.toJSONString(collect));
}
}

View File

@ -0,0 +1,75 @@
GET http://localhost:8988//plmservice/test/testRequest
Content-Type: application/json
{}
###
#Rest Api session login
POST http://localhost:80/api/item
Content-Type: application/json
{}
###
#测试配置文件读取
POST {{baseUrl}}/test/testProp
Content-Type: application/json
###
###用户自定义controller
POST {{baseUrl}}/custom/test
Content-Type: application/json
{"param": "456"}
###
POST {{baseUrl}}/watchService/post/DemoStrategyService1Impl
Content-Type: application/json
{"configName": "style"}
###
#测试PLM登出
POST {{baseUrl}}/test/logout
Content-Type: application/json
###
#测试cookie
POST {{baseUrl}}/test/testCookie
Content-Type: application/json
###
###
#测试延迟队列
POST {{baseUrl}}/test/testRabbitMQ
Content-Type: application/json
{"msg": "test delay message"}
###
#测试策略转发实现类 DemoStrategyService1Impl DemoStrategyService2Impl demoStrategyServiceImpl
POST {{baseUrl}}/watchService/post/DemoStrategyService2Impl
Content-Type: application/json
{"user": "admin","type":"style"}
###
#testDemo request
POST {{baseUrl}}/test/testDemo
Content-Type: application/json
{"test": "testjson"}
###
#testRequest
POST {{baseUrl}}/test/testRequest
Content-Type: application/json
{"test": "testjson"}
###

View File

@ -0,0 +1,11 @@
{
"dev": {
"baseUrl": "http://localhost:8088/plmservice"
},
"test": {
"baseUrl": "http://114.55.209.111:8088/plmservice"
},
"tomcat": {
"baseUrl": "http://localhost:8988/plmservice"
}
}

31
enhancement/.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/

71
enhancement/pom.xml Normal file
View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- 父模块 -->
<properties>
<jakarta-json.version>2.0.1</jakarta-json.version>
<elasticsearch.version>7.16.2</elasticsearch.version>
</properties>
<parent>
<artifactId>plmservice</artifactId>
<groupId>com.centricsoftware</groupId>
<version>2.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>enhancement</artifactId>
<version>2.1</version>
<dependencies>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>commons</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.centricsoftware</groupId>
<artifactId>config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>${jakarta-json.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,33 @@
package com.centricsoftware.enhancement.ant;
import com.centricsoftware.commons.em.C8ImportTypeEnum;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface C8Column {
String attributeId();//C8字段ID
String colName() default "";//导入列名
//String类型可在这定义正则表达式;ref类型的可以写Search的xml(这里写yml的变量在变量中写xmlC8Entity中的createXml一样)
//xml中可以写变量比如{name}程序会自动获取实体类中getName值用于替换变量
String valid() default "";
String stringCase() default "";//字符串是否转成大小写upper转大写lower转小写
String path() default "";//路径
C8ImportTypeEnum type() default C8ImportTypeEnum.STRING;//字段类型
String timeFormat() default "yyyy-MM-dd";//时间格式
boolean update() default true;//字段是否更新
boolean required() default true;//字段是否必填
boolean forceUpdate() default false;//是否强制更新,true表示如果值为空c8的数据将被设置为空
boolean convertParentForceUpdate() default false;//强制更新是否以字段级别的配置为准默认为false
boolean key() default false; //用来判断是新增还是更新
String enumPrefix() default "";//enum值的前缀不需要加冒号
String refBO() default "";//当type为ref类型时在这里注明哪个BO
String refAttr() default "Node Name";//当type为ref类型时默认根据Node Name匹配
//ref类型过滤xml Active
String split() default ";";//当字段为数组时默认的分隔符号
String tips() default "";//重新定制错误信息
String otherXmlAttr() default "";//保存的时候其他属性flag等例子 otherXmlAttr="FG='0x1'"
}

Some files were not shown because too many files have changed in this diff Show More