Commit ff0f3b11 authored by 曹志's avatar 曹志

API模块

parent c5760d13
This diff is collapsed.
......@@ -7,6 +7,7 @@
<module>spacetech-common-util</module>
<module>spacetech-service-interface</module>
<module>spacetech-service-growth</module>
<module>spacetech-service-api</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
......
......@@ -180,6 +180,12 @@
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<exclusions>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
\ No newline at end of file
<?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">
<parent>
<artifactId>spacetech-cloud</artifactId>
<groupId>com.spacetech</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spacetech-service-api</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.spacetech</groupId>
<artifactId>spacetech-service-interface</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.spacetech</groupId>
<artifactId>spacetech-common-util</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- ueditor编辑器使用 end -->
<dependency>
<groupId>com.baidu</groupId>
<artifactId>ueditor</artifactId>
<version>1.1.2</version>
</dependency>
<!--hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
<!--使用resteasy netty发布rest服务 -->
<!--<dependency>-->
<!--<groupId>org.jboss.resteasy</groupId>-->
<!--<artifactId>resteasy-netty4</artifactId>-->
<!--<version>3.9.3.Final</version>-->
<!--<exclusions>-->
<!--<exclusion>-->
<!--<artifactId>httpclient</artifactId>-->
<!--<groupId>org.apache.httpcomponents</groupId>-->
<!--</exclusion>-->
<!--</exclusions>-->
<!--</dependency>-->
<!-- resteasy-jaxrs -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.13.0.Final</version>
</dependency>
<!-- tomcat-embed-core -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.30</version>
</dependency>
<!-- JAX对fastjson支持 -->
<dependency>
<groupId>com.colobu</groupId>
<artifactId>fastjson-jaxrs-json-provider</artifactId>
<version>0.3.2</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.baidu.ueditor.upload;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Base64Uploader {
private static Logger logger = LoggerFactory.getLogger(Base64Uploader.class);
public static State save(String content, Map<String, Object> conf) {
byte[] data = decode(content);
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validSize(data, maxSize)) {
return new BaseState(false, AppInfo.MAX_SIZE);
}
String suffix = FileType.getSuffix("JPG");
String savePath = PathFormat.parse((String) conf.get("savePath"),
(String) conf.get("filename"));
savePath = savePath + suffix;
logger.info("put qiniu filename Base64Uploader ueditor savePath=" + savePath);
State storageState = StorageManager.saveBinaryFile(data, savePath);
if (storageState.isSuccess()) {
// storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", "");
}
return storageState;
}
private static byte[] decode(String content) {
return Base64.decodeBase64(content);
}
private static boolean validSize(byte[] data, long length) {
return data.length <= length;
}
}
\ No newline at end of file
package com.baidu.ueditor.upload;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
public class BinaryUploader {
private static Logger logger = LoggerFactory.getLogger(BinaryUploader.class);
public static final State save(HttpServletRequest request,
Map<String, Object> conf) {
InputStream fileStream = null;
if (!ServletFileUpload.isMultipartContent(request)) {
return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
}
try {
//修改了百度使用原生的commons上传方式
//创建ServletFileUpload实例
ServletFileUpload fileUpload = new ServletFileUpload();
//解析request请求 返回FileItemStream的iterator实例
FileItemIterator iter = fileUpload.getItemIterator(request);
InputStream is = null;//输出流
//迭代取出
while (iter.hasNext()){
FileItemStream item = iter.next();//获取文件流
is = item.openStream();//得到对应表单的输出流
if (!item.isFormField()){//如果是非文件域,设置进入map,这里要注意多值处理
return processFile(conf, is, item);
}
}
if (fileStream == null) {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
} catch (ClassCastException e) {
e.printStackTrace();
return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
}catch (IOException e){
e.printStackTrace();
return new BaseState(false, AppInfo.IO_ERROR);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new BaseState(false, AppInfo.IO_ERROR);
}
logger.info("put qiniu filename BinaryUploader ueditor savePathIO_ERROR=");
return new BaseState(false, AppInfo.IO_ERROR);
}
public static State processFile(Map<String, Object> conf, InputStream is,
FileItemStream item) throws IOException {
String originFileName;
if (is.available()>0){//如果输出流的内容大于0
originFileName = item.getName();//获取文件名
//Streams.copy(fileStream,new FileOutputStream("/Users/hbz/work/"+originFileName),true);//拷贝内容到上传路径
//params.put(name,new String[]{fname});//把文件名设置进request中
//fileStream= is;
String suffix = FileType.getSuffixByFilename(originFileName);
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
State storageState = StorageManager.saveFileByInputStream(is,
originFileName, maxSize);
is.close();
if (storageState.isSuccess()) {
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName);
}
return storageState;
}
return new BaseState(false, AppInfo.REMOTE_FAIL);
}
public String upload(HttpServletRequest request) {
//创建ServletFileUpload实例
ServletFileUpload fileUpload = new ServletFileUpload();
try {
//解析request请求 返回FileItemStream的iterator实例
FileItemIterator iter = fileUpload.getItemIterator(request);
InputStream is = null;//输出流
//迭代取出
while (iter.hasNext()){
FileItemStream item = iter.next();//获取文件流
String name = item.getFieldName();//返回表单中标签的name值
is = item.openStream();//得到对应表单的输出流
if (item.isFormField()){//如果是非文件域,设置进入map,这里要注意多值处理
//setFormParam(name,is);//如果不是文件上传,处理
}else {
if (is.available()>0){//如果输出流的内容大于0
String fname = item.getName();//获取文件名
Streams.copy(is,new FileOutputStream("/Users/hbz/work/"+fname),true);//拷贝内容到上传路径
//params.put(name,new String[]{fname});//把文件名设置进request中
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "upload complete !";
}
private static boolean validType(String type, String[] allowTypes) {
List<String> list = Arrays.asList(allowTypes);
return list.contains(type);
}
}
package com.baidu.ueditor.upload;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.spacetech.common.utils.OSSClientUtil;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.framework.SystemContext;
import com.spacetech.provider.ApiProvider;
public class StorageManager {
public static final int BUFFER_SIZE = 8192;
private static Logger logger = LoggerFactory.getLogger(StorageManager.class);
public StorageManager() {
}
public static State saveBinaryFile(byte[] data, String path) {
logger.info("put qiniu filename ueditor saveBinaryFile=" + path);
File file = getTmpFile(path);
State state = valid(file);
if (!state.isSuccess()) {
return state;
}
File tmpFile = getTmpFile(file.getName());
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
bos.write(data);
bos.flush();
bos.close();
} catch (IOException ioe) {
logger.error("文件上传失败 path=" + path, ioe);
return new BaseState(false, AppInfo.IO_ERROR);
}
state = saveTmpFile(tmpFile, file.getName());
return state;
}
public static State saveFileByInputStream(InputStream is, String originFileName, long maxSize) {
State state = null;
logger.info("put qiniu filename ueditor saveFileByInputStream originFileName=" + originFileName);
File tmpFile = getTmpFile(originFileName);
byte[] dataBuf = new byte[2048];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bos.flush();
bos.close();
if (tmpFile.length() > maxSize) {
tmpFile.delete();
return new BaseState(false, AppInfo.MAX_SIZE);
}
state = saveTmpFile(tmpFile, originFileName);
if (!state.isSuccess()) {
tmpFile.delete();
}
return state;
} catch (IOException e) {
logger.error("文件上传失败 originFileName=" + originFileName, e);
}
return new BaseState(false, AppInfo.IO_ERROR);
}
public static State saveFileByInputStream(InputStream is, String path) {
State state = null;
logger.info("put qiniu filename ueditor saveFileByInputStream1 path=" + path);
File tmpFile = getTmpFile("");
byte[] dataBuf = new byte[2048];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bos.flush();
bos.close();
state = saveTmpFile(tmpFile, path);
if (!state.isSuccess()) {
tmpFile.delete();
}
return state;
} catch (IOException e) {
logger.error("文件上传失败 path=" + path, e);
}
return new BaseState(false, AppInfo.IO_ERROR);
}
private static File getTmpFile(String suffix) {
JSONObject fileParams = SystemContext.baseParams;
String localfileDic = fileParams.getString("localfileDic");
String localfileInternet = fileParams.getString("localfileInternet");
Boolean saveLocalfile = fileParams.getBoolean("saveLocalfile");
File tmpDir = null;
if (StringUtil.isNotEmpty(localfileDic) && saveLocalfile) {
logger.info("put qiniu filename ueditor localfileDic=" + localfileDic + " saveLocalfile=" + saveLocalfile + " localfileInternet=" + localfileInternet);
tmpDir = new File(localfileDic);
} else {
logger.info("put qiniu filename ueditor getTempDirectory=" + localfileDic + " saveLocalfile=" + saveLocalfile + " localfileInternet=" + localfileInternet);
tmpDir = FileUtils.getTempDirectory();
}
String tmpFileName = (Math.random() * 10000 + "").replace(".", "") + suffix;
return new File(tmpDir, tmpFileName);
}
public static State saveTmpFile(File tmpFile, String originFileName) {
State state = null;
String url = "";
String picUrl = "";
JSONObject fileParams = SystemContext.baseParams;
String localfileDic = fileParams.getString("localfileDic");
String localfileInternet = fileParams.getString("localfileInternet");
Boolean saveLocalfile = fileParams.getBoolean("saveLocalfile");
try {
logger.info("put qiniu filename ueditor localfileDic=" + localfileDic + " saveLocalfile=" + saveLocalfile + " localfileInternet=" + localfileInternet
+ " absolutePath()=" + tmpFile.getAbsolutePath());
// url = OSSClientUtil.putFile(tmpFile.getAbsolutePath(), false,
// false,
// saveLocalfile, localfileInternet);
Map fileAndThum = OSSClientUtil.putFileHaveThumbnail(tmpFile.getAbsolutePath(), false, ApiProvider.INTERNAL_OSS, saveLocalfile, localfileInternet, "");
logger.info("putFileHaveThumbnail localfileDic=" + localfileDic + " saveLocalfile=" + saveLocalfile + " localfileInternet=" + localfileInternet + " absolutePath()="
+ tmpFile.getAbsolutePath() + " fileAndThum=" + JSON.toJSONString(fileAndThum));
url = StringUtil.getNullStr(fileAndThum.get("url"));
picUrl = StringUtil.getNullStr(fileAndThum.get("picUrl"));
} catch (IOException e) {
logger.error("文件上传失败IO originFileName=" + originFileName, e);
return new BaseState(false, AppInfo.IO_ERROR);
} catch (Exception e) {
logger.error("文件上传失败 originFileName=" + originFileName, e);
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true);
state.putInfo("size", tmpFile.length());
state.putInfo("title", originFileName);
state.putInfo("url", url.replace(OSSClientUtil.ALI_COMMON_URL, OSSClientUtil.ALI_IMAGE_URL));
state.putInfo("picUrl", picUrl);
return state;
}
public static State saveTmpFile(String absolutePath, String originFileName, int fileSize) {
State state = null;
String url = "";
String picUrl = "";
JSONObject fileParams = SystemContext.baseParams;
String localfileInternet = fileParams.getString("localfileInternet");
Boolean saveLocalfile = fileParams.getBoolean("saveLocalfile");
try {
// Map fileAndThum =
// OSSClientUtil.putFileAndThumbnail(tmpFile.getAbsolutePath(),false);
url = OSSClientUtil.putFile(absolutePath, false, ApiProvider.INTERNAL_OSS, saveLocalfile, localfileInternet);
// url = StringUtil.getNullStr(fileAndThum.get("url"));
// picUrl = StringUtil.getNullStr(fileAndThum.get("picUrl"));
} catch (Exception e) {
logger.error("文件上传失败 path=" + absolutePath+" originFileName="+originFileName, e);
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true);
state.putInfo("size", fileSize);
state.putInfo("title", originFileName);
state.putInfo("url", url.replace(OSSClientUtil.ALI_COMMON_URL, OSSClientUtil.ALI_IMAGE_URL));
state.putInfo("picUrl", picUrl);
return state;
}
private static State valid(File file) {
File parentPath = file.getParentFile();
if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
}
if (!parentPath.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
return new BaseState(true);
}
}
package com.spacetech;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableDiscoveryClient
@EnableJpaRepositories(basePackages = "com.spacetech.dao")
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
package com.spacetech.dao;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.spacetech.entity.OauthToken;
public interface OauthTokenDao
extends PagingAndSortingRepository<OauthToken, String>, JpaSpecificationExecutor<OauthToken> {
@Query(value = "SELECT * FROM oauth_token limit 1", nativeQuery = true)
OauthToken list();
}
package com.spacetech.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "oauth_token")
public class OauthToken implements Serializable {
private static final long serialVersionUID = -3972468206541958509L;
@Id
private String id;
private String appid;
private String appSecret;
private String accessToken;
private String refreshToken;
private Integer expires_in; //到期时间
private Long creatorid;
private Date create_time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public Long getCreatorid() {
return creatorid;
}
public void setCreatorid(Long creatorid) {
this.creatorid = creatorid;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
}
package com.spacetech.framework;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.FileUtil;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.provider.ApiProvider;
import com.spacetech.util.MemCacheForOnecardUtil;
import com.spacetech.util.MemCacheUtil;
/**
*
* @author wm web工程上下文
*/
public final class SystemContext {
private String memcacheutilIpPort;
private String memcacheutilUsername;
private String memcacheutilPassword;
private String memcacheforonecardutilIpPort;
private String memcacheforonecardutilUsername;
private String memcacheforonecardutilPassword;
private Boolean internalOss = false;
private Boolean saveLocalfile = false;
private String localfileDic = "";
private String localfileInternet;
public final static JSONObject baseParams = new JSONObject();
public static String SERVER_IP_ADDRESS = "";
public void init() {
// 初始化参数配置
// ConfigUtil.loadProperties("jdbc.properties");
if (StringUtil.isNullOrEmpty(memcacheutilIpPort) || memcacheutilIpPort.indexOf(":") < 0) {
throw new RuntimeException("缓存未配置或者格式有误(127.0.0.1:11211)");
}
if (StringUtil.isNullOrEmpty(localfileDic)) {
throw new RuntimeException("Zookeeper未配置本地存储目录路径");
}
FileUtil.makeDir(localfileDic);
if (saveLocalfile && StringUtil.isNullOrEmpty(localfileInternet)) {
throw new RuntimeException("Zookeeper未配置本地访问路径");
}
baseParams.put("saveLocalfile", saveLocalfile);
baseParams.put("localfileDic", localfileDic);
baseParams.put("localfileInternet", localfileInternet);
baseParams.put("internalOss", internalOss);
if (StringUtil.isNotEmpty(memcacheutilUsername)
&& !ConstantVar.SPACE_PLACEHOLDER.equals(memcacheutilUsername)) {
MemCacheUtil.start(memcacheutilIpPort, memcacheutilUsername, memcacheutilPassword);
} else {
MemCacheUtil.start(memcacheutilIpPort);
}
if (StringUtil.isNotEmpty(memcacheforonecardutilUsername)
&& !ConstantVar.SPACE_PLACEHOLDER.equals(memcacheforonecardutilUsername)) {
MemCacheForOnecardUtil.start(memcacheforonecardutilIpPort, memcacheforonecardutilUsername,
memcacheforonecardutilPassword);
} else {
MemCacheForOnecardUtil.start(memcacheforonecardutilIpPort);
}
ApiProvider.INTERNAL_OSS = internalOss;
initIpAddrList();
}
public String getMemcacheutilIpPort() {
return memcacheutilIpPort;
}
public void setMemcacheutilIpPort(String memcacheutilIpPort) {
this.memcacheutilIpPort = memcacheutilIpPort;
}
public String getMemcacheutilUsername() {
return memcacheutilUsername;
}
public void setMemcacheutilUsername(String memcacheutilUsername) {
this.memcacheutilUsername = memcacheutilUsername;
}
public String getMemcacheutilPassword() {
return memcacheutilPassword;
}
public void setMemcacheutilPassword(String memcacheutilPassword) {
this.memcacheutilPassword = memcacheutilPassword;
}
public String getMemcacheforonecardutilIpPort() {
return memcacheforonecardutilIpPort;
}
public void setMemcacheforonecardutilIpPort(String memcacheforonecardutilIpPort) {
this.memcacheforonecardutilIpPort = memcacheforonecardutilIpPort;
}
public String getMemcacheforonecardutilUsername() {
return memcacheforonecardutilUsername;
}
public void setMemcacheforonecardutilUsername(String memcacheforonecardutilUsername) {
this.memcacheforonecardutilUsername = memcacheforonecardutilUsername;
}
public String getMemcacheforonecardutilPassword() {
return memcacheforonecardutilPassword;
}
public void setMemcacheforonecardutilPassword(String memcacheforonecardutilPassword) {
this.memcacheforonecardutilPassword = memcacheforonecardutilPassword;
}
public Boolean getSaveLocalfile() {
return saveLocalfile;
}
public void setSaveLocalfile(Boolean saveLocalfile) {
this.saveLocalfile = saveLocalfile;
}
public String getLocalfileDic() {
return localfileDic;
}
public void setLocalfileDic(String localfileDic) {
this.localfileDic = localfileDic;
}
public String getLocalfileInternet() {
return localfileInternet;
}
public void setLocalfileInternet(String localfileInternet) {
this.localfileInternet = localfileInternet;
}
public Boolean getInternalOss() {
return internalOss;
}
public void setInternalOss(Boolean internalOss) {
this.internalOss = internalOss;
}
public static void initIpAddrList() {
try {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
if (null != netint.getHardwareAddress()) {
List<InterfaceAddress> list = netint.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : list) {
String localipstr = interfaceAddress.getAddress().toString();
String localip = localipstr.substring(1, localipstr.length());
if (localip.startsWith("10.")) {
SERVER_IP_ADDRESS = localip;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.spacetech.framework.hibernate;
import org.apache.commons.lang.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class ImprovedNamingStrategy implements PhysicalNamingStrategy {
@Override
public Identifier toPhysicalCatalogName(Identifier identifier,
JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalColumnName(Identifier identifier,
JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSchemaName(Identifier identifier,
JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSequenceName(Identifier identifier,
JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalTableName(Identifier identifier,
JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
private Identifier convert(Identifier identifier) {
if (identifier == null || StringUtils.isBlank(identifier.getText())) {
return identifier;
}
String regex = "([a-z])([A-Z])";
String replacement = "$1_$2";
String newName = identifier.getText().replaceAll(regex, replacement)
.toLowerCase();
return Identifier.toIdentifier(newName);
}
}
\ No newline at end of file
package com.spacetech.provider;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spacetech.service.ProviderService;
import com.spacetech.service.RestApiHub;
import com.spacetech.util.LogServer;
import com.spacetech.websocketchat.TextWebSocketFrameHandler;
import com.spacetech.websocketchat.WebsocketChatServer;
import com.spacetech.websocketchat.ClassbrandWebsocket.TextWebSocketClassBrandFrameHandler;
import com.spacetech.websocketchat.ClassbrandWebsocket.WebsocketClassBrandServer;
import com.spacetech.websocketcomment.CommentSocketFrameHandler;
import com.spacetech.websocketcomment.WebsocketCommentThread;
public class ApiProvider {
private static Logger logger = LoggerFactory.getLogger(ApiProvider.class);
public static boolean INTERNAL_OSS = false;
public static void main(String[] args) {
// String zookeeperAddress = "";
// if (args != null && args.length > 0) {
// zookeeperAddress = args[0];
// logger.error("Zookeeper argu zookeeperAddress=" + zookeeperAddress);
// } else {
// zookeeperAddress = ConfigUpdater.ZK_ADDRESS;
// logger.error("Zookeeper argu error,user local config zookeeperAddress=" + zookeeperAddress);
//
// }
// ZookeeperClientUtil.init(zookeeperAddress, ConfigUpdater.PATH);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/spring-context.xml");
context.start();
ProviderService providerService = (ProviderService) context.getBean("providerService");
LogServer.setProviderService(providerService);
runThread(new LogServer(), 15);
RestApiHub restApiHub = (RestApiHub) context.getBean("restApiHub");
Thread commentThread = new Thread(new WebsocketCommentThread(8001));
commentThread.start();
try {
new WebsocketChatServer(8000).run();
new WebsocketClassBrandServer(9000).run();
} catch (Exception e) {
logger.error(e.toString());
}
System.out.println("服务已经启动...");
synchronized (ApiProvider.class) {
while (true) {
try {
ApiProvider.class.wait();
} catch (Throwable e) {
}
}
}
}
private static void runThread(Runnable run, int loop) {
ExecutorService pool = Executors.newFixedThreadPool(loop);
for (int i = 0; i < loop; i++) {
pool.execute(run);
}
}
}
package com.spacetech.service;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.logger.LoggerUtil;
import com.spacetech.common.utils.ApiUtil;
import com.spacetech.common.utils.HttpClientUtil;
import com.spacetech.common.utils.JsonUtil;
import com.spacetech.gateway.ApiEndpointApiHub;
public class ApiEndpointApiHubImpl implements ApiEndpointApiHub {
private static Logger logger = LoggerFactory
.getLogger(ApiEndpointApiHubImpl.class);
@Autowired
private OauthTokenService oauthTokenService;
public String callApi(String apiMethod, Boolean readonly, JSONObject param) {
try {
LoggerUtil.setMdcRequestId(param.getString("requestId"));
logger.info("before apiMethod=" + apiMethod + " 入参:" + JSON.toJSONString(param) + " readonly=" + readonly);
String result = "";
if (readonly) {
result= this.query(apiMethod, param);
} else {
result= this.update(apiMethod, param);
}
logger.info("after apiMethod=" + apiMethod + " result=" + result);
return result;
} catch (ApiException e) {
String errorMsg = e.getErrorMsg();
if (errorMsg != null && errorMsg.indexOf("发生异常:") > -1) {
errorMsg = errorMsg.substring(errorMsg.indexOf("【发生异常:") + 6,
errorMsg.indexOf("】"));
}
logger.error(apiMethod + "发生了API Exception的错误," + errorMsg+" 入参:" + JSON.toJSONString(param),e);
return JsonUtil
.formatJsonResult(apiMethod, "", "500", errorMsg, "");
} catch (Exception e) {
logger.error(apiMethod + "发生了非API Exception的错误,入参:" + JSON.toJSONString(param), e);
String resultCode = "500";
String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils
.getFullStackTrace(e);
String resultMsg = fullStackTrace;
return JsonUtil.formatJsonResult(apiMethod, "", resultCode,
resultMsg, "");
}
}
/**
* 需要走事务通道
*
* @param apiMethod
* @param
* @return
*/
@Transactional(readOnly = false)
public String update(String apiMethod, JSONObject param) {
return this.callApiMethod(apiMethod, param);
}
/**
* 不用走事务通道
*
* @param apiMethod
* @param
* @return
*/
public String query(String apiMethod, JSONObject param) {
return this.callApiMethod(apiMethod, param);
}
/**
* 调用API的通用方法<BR>
* <BR>
* 通过反射找到对应的api以及api方法,并对调用结果进行封装
*
* @param apiMethod
* 要调用的api方法,格式[API/METHOD],ServiceFactory会根据API+
* Service定位到具体的api类,并根据反射找到要执行的方法并进行调用
* @return
*/
@SuppressWarnings("rawtypes")
public String callApiMethod(String apiMethod, JSONObject params) {
Object methodResult = null;
String resultCode = ApiUtil.SUCCESS;
String resultMsg = "";
// 如果是模拟输入
if (ApiUtil.isMockCall(params)) {
HashMap<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("api", apiMethod);
Map<String, String> resultMap;
try {
resultMap = HttpClientUtil.submitPostRequest(
ApiUtil.MOCK_SERVER_URL, paramsMap, null);
String status = resultMap.get("status");
if ("200".equals(status)) {
return resultMap.get("responseMessage");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "error";
}
// return apiMockService.callMockApi(apiMethod, params);
} else {
String[] apiMethods = apiMethod.split("_");
String apiName = apiMethods[0];
String methodName = apiMethods[1];
// JSONObject result = new JSONObject();
try {
Class[] argsClass = ApiUtil.getJsonArgClass();
if ("oauthtoken".equals(apiName)) {
Method method = oauthTokenService.getClass().getMethod(
methodName, argsClass);
methodResult = method.invoke(oauthTokenService, params);
} else {
// 服务不存在
resultCode = ApiUtil.ERROR_CLASS_NOTEXISTS;
resultMsg = apiMethod + "对应的服务类不存在";
}
} catch (ApiException e) {
logger.warn("API ApiException apiMethod=" + apiMethod + " 错误原因:" + e.getMessage());
throw e;
} catch (java.lang.reflect.InvocationTargetException e) {
logger.error(
"API InvocationTargetException apiMethod=" + apiMethod + " 入参数=" + JSON.toJSONString(params),
e);
throw new ApiException(e.getTargetException().getMessage());
} catch (NoSuchMethodException e) {
logger.error("API NoSuchMethodException apiMethod=" + apiMethod, e);
throw new ApiException("【" + apiMethod + "】服务方法未注册!");
} catch (Exception e) {
logger.error("API Exception apiMethod=" + apiMethod + " 入参数=" + JSON.toJSONString(params), e);
throw new RuntimeException(e);
}
}
return ApiUtil.formatJsonResult(apiMethod, methodResult, resultCode,
resultMsg, "");
}
}
package com.spacetech.service;
public class ApiException extends RuntimeException {
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Throwable getErrorCause() {
return errorCause;
}
public void setErrorCause(Throwable errorCause) {
this.errorCause = errorCause;
}
private static final long serialVersionUID = -9171287832448832971L;
protected String errorMsg; // 错误信息(For debug)
protected Throwable errorCause = null; // 错误发生原因(原始Exception)
public ApiException(Throwable e, String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
this.errorCause = e;
}
public ApiException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package com.spacetech.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.dao.OauthTokenDao;
import com.spacetech.entity.OauthToken;
@Component
@Transactional(readOnly = true)
public class OauthTokenService {
@Autowired
private OauthTokenDao oauthTokenDao;
/***
* 接口:oauthToken_list
*
* 测试接口
*
* @param params
* @return
*/
@Transactional(readOnly = false)
public OauthToken list(JSONObject params) {
String id = params.getString("id");
return oauthTokenDao.list();
}
}
package com.spacetech.service;
import com.spacetech.common.utils.JsonUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.gateway.BaseDataApiHub;
import com.spacetech.gateway.LogApiHub;
import com.spacetech.gateway.TokenApiHub;
import com.spacetech.gateway.UserApiHub;
/**
* 业务dubbox服务,需要依赖其他dubbo服务
*
* @author hbz
*
*/
@Component
@Transactional(readOnly = true)
public class ProviderService {
private static Logger logger = LoggerFactory.getLogger(ProviderService.class);
@Reference
private UserApiHub userApiHub;
@Reference
private BaseDataApiHub baseDataApiHub;
@Reference
private LogApiHub logApiHub;
@Reference
private TokenApiHub tokenApiHub;
/**
* 异步保存日志 后续直接将需要保存的数据丢到metaq
*
* @param
* @return
*/
public String saveInterfaceLog(JSONObject params) {
// JSONObject pidparams = new JSONObject();
// pidparams.put("openid", openid);
String json = "";
try {
json = logApiHub.callApiAsync("log_saveInterfaceLog", false, params);
} catch (Exception e) {
logger.error("日志记录发生错误,错误原因:" + e.getMessage());
}
return json;
}
/**
* 校验token
*
* @param campusid
* @param token
* @return
*/
public JSONObject checkToken(String apiMethod, Long campusid, String token) {
JSONObject pidparams = new JSONObject();
pidparams.put("campusid", campusid);
pidparams.put("token", token);
String json = tokenApiHub.callApi("oauth_checkToken", true, pidparams);
return JSON.parseObject(json);
}
public void saveLog(JSONObject params) {
try {
logApiHub.callApiAsync("log_saveLog", false, params);
} catch (Exception e) {
}
}
public String getParentName(Long stuid, int relationCode) {
JSONObject params = new JSONObject();
params.put("stuid", stuid);
params.put("relationCode", relationCode);
String json = baseDataApiHub.callApi("stu_getParentName", true,params);
return JsonUtil.formatNullStr(json);
}
}
package com.spacetech.service;
public interface RestApiHub {
/**
* 调用API
*
* @return
*/
public String callApi(String api, String param);
public String callApi(String param);
public String callPcApi(String api, String param);
public String receiveNodataApiPost(String api);
public String receiveNodataApiGet(String api);
public String receiveWechatApiPost(String api);
public String receiveWechatApiGet(String api);
public String receiveWechatPayApiPost();
public String receivePcWechatPayApiPost();
public String receiveWechatPayApiPost(String api);
public String initUeditorGet();
public String initUeditorPost();
public String init135Ueditor(String filter);
public String thirdReq(String api);
public String thirdGetReq(String api);
public String callUploadFileApi(String api);
public String callEndpointApi(String api, String param);
public String callClassBrandApi(String param);
public String callUploadApi(String api);
public String callClassBrandStateApi(String param);
public String saveExamByYdb(String param);
public String saveScoreByYdb(String param);
public String xiumiGetAccessToken();
public String xiumiGetPicUrl();
public String xiumiSaveArticles(String param);
}
package com.spacetech.service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.gateway.PortalApiHub;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
@Service
@Transactional(readOnly = true)
public class XiuMiService {
private static Logger logger = LoggerFactory.getLogger(XiuMiService.class);
@Autowired
private RestApiHubImpl restApiHubImpl;
private static final String XIUMI_SECRET = "Thie1ba6guke7quoh6veikae3Ierukoh";
private static final String XIUMI_APPID = "eZeecee1aich1aetoh4jooquauqua1ah";
private static final String XIUMI_TOKEN = "Uighuo5EiNguoWoh4nohf7Jaina0il8s";
private static final Long TWELVE_HOURS_SECOND = DateUnit.HOUR.getMillis() * 12 / 1000;
private static final String ACCESS_TOKEN_KEY = "kSA4w7nAYjjveaADreqIZw==";
private static final SymmetricCrypto ACCESS_TOKEN_CRYPTO = new SymmetricCrypto(SymmetricAlgorithm.AES,
Base64.decode(ACCESS_TOKEN_KEY));
enum ErrorCode {
CHECK_APPID_ERROR(-3, "APPID错误"), CHECK_ACCESS_TOKEN_ERROR(-2, "access_token校验失败"),
CHECK_SIGNATURE_ERROR(-1, "签名校验失败"), SUCCESS(0, "success"), PARAM_MISSING_ERROR(1, "参数不完整"),
PHOTO_UPLOAD_ERROR(2, "图片上传失败"), ARTICLES_SAVE_ERROR(3, "图文保存失败");
private final Integer code;
private final String msg;
ErrorCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
/**
* 接收图文内容
*
* @param request
* @param portalApiHub
* @return
*/
@Transactional
public JSONObject saveArticles(HttpServletRequest request, JSONObject articlesJson, PortalApiHub portalApiHub) {
// 鉴权
JSONObject checkJson = checkParams(request);
Integer checkCode = checkJson.getInteger("code");
if (!ErrorCode.SUCCESS.code.equals(checkCode)) {
return getRetJson(checkCode, checkJson.getString("msg"), getReceivePhotoDataJson(null, null));
}
articlesJson.put("uid", request.getParameter("uid"));
String resultStr = portalApiHub.callApi("record_saveXiumiArticles", true, articlesJson);
if (!ConstantVar.PRAISE_RETURN_SUCCESS.equals(JSONObject.parseObject(resultStr).getString("data"))) {
logger.warn("xiumi saveArticles ARTICLES_SAVE_ERROR resultStr = {}", new Object[] { resultStr });
return getRetJson(ErrorCode.ARTICLES_SAVE_ERROR.code, ErrorCode.ARTICLES_SAVE_ERROR.msg, null);
}
// 保存图文
return getRetJson(ErrorCode.SUCCESS.code, ErrorCode.SUCCESS.msg, null);
}
/**
* 获取鉴权状态JSON
*
* @param request 请求
* @return 返回的JSON
*/
public JSONObject getAccessToken(HttpServletRequest request) {
String appid = request.getParameter("appid");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String signature = request.getParameter("signature");
if (!XIUMI_APPID.equals(appid)) {
logger.warn("xiumi getAccessToken CHECK_APPID_ERROR appid = {}, timestamp = {}, nonce = {}, signature = {}",
new Object[] { appid, timestamp, nonce, signature });
return getRetJson(ErrorCode.CHECK_APPID_ERROR.code, ErrorCode.CHECK_APPID_ERROR.msg, new JSONObject());
}
if (StrUtil.hasEmpty(appid, timestamp, nonce, signature)) {
return getRetJson(ErrorCode.PARAM_MISSING_ERROR.code, ErrorCode.PARAM_MISSING_ERROR.msg, new JSONObject());
}
List<String> signList = Arrays.asList(XIUMI_SECRET, timestamp, nonce, appid);
signList.sort(String::compareTo);
String unencryptedSignature = String.join("", signList);
String encryptedSignature = SecureUtil.md5(SecureUtil.md5(unencryptedSignature));
if (!signature.equals(encryptedSignature)) {
logger.warn(
"xiumi getAccessToken CHECK_SIGNATURE_ERROR appid = {}, timestamp = {}, nonce = {}, signature = {}",
new Object[] { appid, timestamp, nonce, signature });
return getRetJson(ErrorCode.CHECK_SIGNATURE_ERROR.code, ErrorCode.CHECK_SIGNATURE_ERROR.msg,
new JSONObject());
}
return getAccessTokenRetJson();
}
private JSONObject getAccessTokenRetJson() {
JSONObject retJson = new JSONObject();
retJson.put("access_token", ACCESS_TOKEN_CRYPTO.encrypt(String.valueOf(DateUtil.date().getTime())));
retJson.put("expires_in", TWELVE_HOURS_SECOND);
return retJson;
}
/**
* 请求数据二进制->URL
*
* @param request 请求
* @return 返回参数Json
*/
public JSONObject getPicUrl(HttpServletRequest request) {
// 鉴权
JSONObject checkJson = checkParams(request);
Integer checkCode = checkJson.getInteger("code");
if (!ErrorCode.SUCCESS.code.equals(checkCode)) {
return getRetJson(checkCode, checkJson.getString("msg"), getReceivePhotoDataJson(null, null));
}
@SuppressWarnings("unchecked")
Map<String, String> fileMap = (Map<String, String>) restApiHubImpl.transformationRequest(request);
String url = fileMap.get("url");
if (StringUtil.isNullOrEmpty(url)) {
logger.warn("xiumi getPicUrl PHOTO_UPLOAD_ERROR url = {}, fileMap.isEmpty() = {}",
new Object[] { url, fileMap.isEmpty() });
return getRetJson(ErrorCode.PHOTO_UPLOAD_ERROR.code, ErrorCode.PHOTO_UPLOAD_ERROR.msg,
getReceivePhotoDataJson(null, null));
}
return getRetJson(ErrorCode.SUCCESS.code, ErrorCode.SUCCESS.msg, getReceivePhotoDataJson(url, null));
}
private JSONObject getRetJson(Integer code, String msg, JSONObject dataJson) {
JSONObject retJson = new JSONObject();
retJson.put("code", Objects.isNull(code) ? -1 : code);
retJson.put("msg", StringUtil.getNullStr(msg));
if (Objects.nonNull(dataJson)) {
retJson.put("data", dataJson);
}
return retJson;
}
private JSONObject getReceivePhotoDataJson(String url, String name) {
JSONObject dataJson = new JSONObject();
dataJson.put("url", StringUtil.getNullStr(url));
dataJson.put("name", StringUtil.getNullStr(name));
return dataJson;
}
/**
* 输入参数校验的错误code均为负数
*/
private JSONObject checkParams(ServletRequest request) {
String accessToken = request.getParameter("access_token");
String timestamp = request.getParameter("timestamp");
String uid = request.getParameter("uid");
String signature = request.getParameter("signature");
if (StrUtil.hasEmpty(accessToken, timestamp, uid, signature)) {
logger.warn(
"xiumi getAccessToken PARAM_MISSING_ERROR accessToken = {}, timestamp = {}, uid = {}, signature = {}",
new Object[] { accessToken, timestamp, uid, signature });
return getRetJson(ErrorCode.PARAM_MISSING_ERROR.code, ErrorCode.PARAM_MISSING_ERROR.msg,
getReceivePhotoDataJson(null, null));
}
if (!checkAccessToken(accessToken)) {
logger.warn(
"xiumi getAccessToken CHECK_ACCESS_TOKEN_ERROR accessToken = {}, timestamp = {}, uid = {}, signature = {}",
new Object[] { accessToken, timestamp, uid, signature });
return getRetJson(ErrorCode.CHECK_ACCESS_TOKEN_ERROR.code, ErrorCode.CHECK_ACCESS_TOKEN_ERROR.msg,
getReceivePhotoDataJson(null, null));
}
String unencryptedSignature = accessToken + timestamp;
String encryptedSignature = SecureUtil.md5(SecureUtil.md5(unencryptedSignature) + uid);
if (!signature.equals(encryptedSignature)) {
logger.warn(
"xiumi getAccessToken CHECK_SIGNATURE_ERROR accessToken = {}, timestamp = {}, uid = {}, signature = {}",
new Object[] { accessToken, timestamp, uid, signature });
return getRetJson(ErrorCode.CHECK_SIGNATURE_ERROR.code, ErrorCode.CHECK_SIGNATURE_ERROR.msg,
getReceivePhotoDataJson(null, null));
}
return getRetJson(ErrorCode.SUCCESS.code, ErrorCode.SUCCESS.msg, getReceivePhotoDataJson(null, null));
}
/**
* 校验accessToken
*
* @param accessToken accessToken
* @return token是否正确
*/
private boolean checkAccessToken(String accessToken) {
try {
byte[] decrypt = ACCESS_TOKEN_CRYPTO.decrypt(accessToken);
String accessTokenStr = new String(decrypt);
long dateBetween = DateUtil.between(DateUtil.date(), DateUtil.date(Long.parseLong(accessTokenStr)),
DateUnit.SECOND);
if (dateBetween > TWELVE_HOURS_SECOND) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
}
package com.spacetech.util;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.entity.WxXxLog;
public class LogQueue {
public static BlockingQueue<JSONObject> logQueue = new ArrayBlockingQueue<JSONObject>(1024 * 1024);
private static Logger logger = LoggerFactory.getLogger(LogQueue.class);
public static void put(WxXxLog log) {
try {
if (log.getAppid() != null && log.getAppid().equals("cache_invalid")) {
return;
}
int lsize = logQueue.size();
if (lsize > 8000) {
logger.warn("put logqueue size max");
return;
} else if (lsize > 0 && lsize % 1000 == 0) {
logger.warn("put logqueue size = " + lsize);
}
JSONObject logJson = new JSONObject();
logJson.put("id", log.getId());
logJson.put("orgcode", log.getOrgcode());
logJson.put("campusid", log.getCampusid());
logJson.put("operatetime", log.getOperatetime());
logJson.put("appid", log.getAppid());
logJson.put("appname", log.getAppname());
logJson.put("apppath", log.getApppath());
logJson.put("userid", log.getUserid());
logJson.put("username", log.getUsername());
logJson.put("ip", log.getIp());
logJson.put("content", log.getContent());
logJson.put("serialnumber", log.getSerialnumber());
logJson.put("time", log.getTime());
logJson.put("result", log.getResult());
logJson.put("refer", log.getRefer());
logJson.put("cookie", log.getCookie());
logJson.put("agent", log.getAgent());
logJson.put("type", log.getType());
logJson.put("url", log.getUrl());
logJson.put("resultStr", log.getResultStr());
logJson.put("resultLength", log.getResultLength());
logJson.put("serverip", log.getServerip());
logJson.put("currCampusid", log.getCurrCampusid());
logJson.put("currCampusName", log.getCurrCampusName());
logJson.put("agentType", log.getAgentType());
logJson.put("usertype", log.getUsertype());
logQueue.put(logJson);
} catch (Exception e) {
logger.error("put logqueue error", e);
}
// logger.info(" 更新后当前logQueue队列数量" + logQueue.size());
}
/**
*
* @return
*/
public static JSONObject take() {
try {
return logQueue.take();
} catch (InterruptedException e) {
return null;
}
}
public static BlockingQueue<JSONObject> getFeedbackQueue() {
return logQueue;
}
}
package com.spacetech.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.exception.BusinessException;
import com.spacetech.service.ProviderService;
public class LogServer implements Runnable {
private static Logger logger = LoggerFactory.getLogger(LogServer.class);
private static ProviderService providerService;
public static ProviderService getProviderService() {
return providerService;
}
public static void setProviderService(ProviderService providerService) {
LogServer.providerService = providerService;
}
/**
* 从总PushMsgQueue消息队列里取数据,并进行处理
*/
@Override
public void run() {
while (true) {
JSONObject log = LogQueue.take();
try {
providerService.saveLog(log);
// logger.info("LOG:" + log.toJSONString());
} catch (BusinessException be) {
logger.error("save log error", be);
} catch (Exception exception) {
logger.error("save log error2", exception);
}
}
}
}
package com.spacetech.util;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.StringUtil;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
public class MemCacheForOnecardUtil {
private static Logger logger = LoggerFactory.getLogger(MemCacheForOnecardUtil.class);
private static final String TYPE_AES_KEY_DATA_SAFE = "AES_KEY_DATA_SAFE";
private static final String TYPE_LOGIN_SESSION = "TYPE_LOGIN_SESSION";
/**
* 设置用户登录缓存
*
* @param user
*/
public static void setLoginSession(JSONObject user) {
if (user != null) {
// 有效期30天
set(getMemcacheKey(TYPE_LOGIN_SESSION, user.getString("ssid")), 30 * 24 * 60 * 60, JSON.toJSONString(user));
}
}
public static JSONObject getLoginSession(String ssid, String openid) {
if (StringUtil.isNullOrEmpty(ssid)) {
return null;
}
Object result = get(getMemcacheKey(TYPE_LOGIN_SESSION, ssid));
if (result == null && StringUtil.isNotEmpty(openid)) {
result = get(getMemcacheKey(TYPE_LOGIN_SESSION, openid));
}
if (result == null) {
return null;
}
JSONObject user = JSON.parseObject((String) result);
return user;
}
/**
* 使用户登录信息失效
*
* @throws MemcachedException
* @throws InterruptedException
* @throws TimeoutException
*/
public static void invalidLoginSession(String userid) {
if (StringUtil.isNotEmpty(userid)) {
delete(getMemcacheKey(TYPE_LOGIN_SESSION, userid));
}
}
private static String getMemcacheKey(String type, String keyid) {
return type + "_" + keyid;
}
/**
* 设置aeskey
*
*/
public static String getAesKeyDataSafe() {
String result = "";
try {
Object obj = get(ConstantVar.SOURCE_YEY + TYPE_AES_KEY_DATA_SAFE);
if (obj != null) {
result = (String) obj;
return result;
} else {
logger.error("获取aeskey错误1 result=" + result);
return null;
}
} catch (Exception e) {
logger.error("获取aeskey错误2 result=" + result, e);
e.printStackTrace();
return null;
}
}
private static MemcachedClient client = null;
public static void start(String ipPort) {
try {
client = new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误", e);
}
}
public static void start(String ipPort, String username, String password) {
AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" }, new PlainCallbackHandler(username, password));
try {
client = new MemcachedClient(
new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY).setAuthDescriptor(ad).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误", e);
}
}
public static void set(String key, Object obj) {
try {
client.set(key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(String key) {
try {
client.delete(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(String key, int expire, Object obj) {
try {
client.set(key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(String key) {
try {
return client.get(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
}
package com.spacetech.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.websocketcomment.CommentSocketFrameHandler;
import net.rubyeye.xmemcached.utils.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
public class MemCacheUtil {
private static Logger logger = LoggerFactory.getLogger(MemCacheUtil.class);
private static MemcachedClient client = null;
private static final String TYPE_WX_USER_INFO = "WX_USER_INFO_NEW";
private static final String LIVE_LIVECOMMENT = "LIVE_LIVECOMMENT";
private static final Integer LIVE_LIVECOMMENT_UNSHOW = 0;
private static final Integer LIVE_LIVECOMMENT_SHOW = 1;
public static void start(String ipPort) {
try {
client = new MemcachedClient(new ConnectionFactoryBuilder()
.setProtocol(Protocol.BINARY).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误", e);
}
}
public static void start(String ipPort,String username,String password) {
AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" },
new PlainCallbackHandler(username, password));
try {
client = new MemcachedClient(
new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
.setAuthDescriptor(ad).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误", e);
}
}
public static void set(String key, Object obj) {
try {
client.set(key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(String key) {
try {
client.delete(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(String key, int expire, Object obj) {
try {
client.set(key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(String key) {
try {
return client.get(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
/**
* 通过用户id获取缓存
*
* @param userid
* @return
*/
public static JSONObject getUserInfoFromMemcached(Long userid) {
if (StringUtil.isNotEmpty(userid)) {
String userinfo = (String) get(TYPE_WX_USER_INFO + ConstantVar.SOURCE_YEY + userid);
if (StringUtil.isNotEmpty(userinfo)) {
return JSON.parseObject(userinfo);
} else {
return null;
}
} else {
return null;
}
}
public static JSONObject putLiveComment(String recordid, String comment) {
try {
JSONObject commentJson = CommentSocketFrameHandler.getLiveComment(comment);
if (StringUtil.isNullOrEmpty(commentJson.size())) {
logger.info("comment send fail! recordid = " + recordid + " comment = " + comment);
return new JSONObject();
}
Object commentList = get(LIVE_LIVECOMMENT + "_" + recordid);
List<JSONObject> commentJsonList = (commentList == null ? null : (List<JSONObject>) commentList);
if (commentJsonList == null) {
Boolean isFinish = new CommentSocketFrameHandler().getLiveState(null, comment, recordid,
CommentSocketFrameHandler.SENDCOMMENT);
if (isFinish) {
logger.info("comment send fail , live isFinish or forbidden! recordid = " + recordid);
return new JSONObject();
}
commentJsonList = Collections.synchronizedList(new ArrayList<JSONObject>());
} else {
Boolean isFinish = new CommentSocketFrameHandler().getLiveState(null, comment, recordid,
CommentSocketFrameHandler.SENDCOMMENT);
if (isFinish) {
logger.info("comment send fail , live isFinish or forbidden! recordid = " + recordid);
return new JSONObject();
}
}
synchronized (commentJsonList) {
commentJsonList.add(commentJson);
set(LIVE_LIVECOMMENT + "_" + recordid, 24 * 60 * 60, commentJsonList);
}
return commentJson;
} catch (Exception e) {
logger.info("comment put cache error! recordid = " + recordid + " comment = " + comment + " e = "
+ e.getMessage(),e);
return new JSONObject();
}
}
public static List<JSONObject> getCommentList(String recordid) {
List<JSONObject> commentJsonList = new ArrayList<JSONObject>();
try {
Object commentList = get(LIVE_LIVECOMMENT + "_" + recordid);
if (commentList != null) {
commentJsonList = (List<JSONObject>) commentList;
commentJsonList = commentJsonList.stream()
.filter(c -> LIVE_LIVECOMMENT_SHOW.equals(c.getInteger("isShow")))
.collect(Collectors.toList());
Integer commentSize = commentJsonList.size();
if (commentSize > CommentSocketFrameHandler.LIVECOMMENT_COMMENTLISTMAXSIZE) {
commentJsonList = CommentSocketFrameHandler.getCommentLimitList(commentJsonList, commentSize);
}
}
return commentJsonList;
} catch (Exception e) {
logger.info("获取直播评论列表失败, recordid = " + recordid);
return new ArrayList<>();
}
}
}
package com.spacetech.util;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.OSSClientUtil;
import com.spacetech.common.utils.StringUtil;
public class WatermarkUtil {
public static String makeWatermark(Long campusid, JSONObject campus, JSONObject campusconfig, String sysconfig) {
String customWatermark = StringUtil
.getNullStr(campusconfig.getString(ConstantVar.CONFIG_CODE_CUSTOMWATERMARK.toString()));
String watermarkConfig = StringUtil
.getNullStr(campusconfig.getString(ConstantVar.CONFIG_CODE_WATERMARK_STATE.toString()));
String wartermarkText = "";
if (StringUtil.isNotEmpty(customWatermark)) {
wartermarkText = customWatermark;
} else {
wartermarkText = StringUtil.getNullStr(campus.get("campus"));
}
if ("1".equals(watermarkConfig)) {
String logo = StringUtil.getNullStr(campus.get("imgpath"));
if (StringUtil.isNotEmpty(logo) && logo.indexOf(OSSClientUtil.ALI_IMAGE_URL) > -1) {
return makeWatermarkWithImg(campusid, logo, wartermarkText);
} else {
return makeWatermarkOnly(campusid, wartermarkText, sysconfig);
}
}
return "";
}
private static String makeWatermarkOnly(Long campusid, String text, String sysconfig) {
return "watermark=2&text=" + URLEncoder.encode(StringUtil.encodeBASE64(text)) + sysconfig;
}
private static String makeWatermarkWithImg(Long campusid, String imgpath, String text) {
return "watermark=3&object="
+ URLEncoder.encode(
StringUtil.encodeBASE64(imgpath.replace(OSSClientUtil.ALI_IMAGE_URL, "") + "@30h_30w_2e"))
+ "&text=" + URLEncoder.encode(StringUtil.encodeBASE64(text))
+ "&type=ZmFuZ3poZW5na2FpdGk&size=16&t=100&color=I0ZGRkZGRg&order=0&align=1&interval=10&p=9&y=10&x=10";
}
}
package com.spacetech.websocketchat.ClassbrandWebsocket;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.service.RestApiHub;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 处理TextWebSocketFrame
*
*/
@Component
public class TextWebSocketClassBrandFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static Logger logger = LoggerFactory.getLogger(TextWebSocketClassBrandFrameHandler.class);
public static Map<Channel, String> channelClassBrandMap = new ConcurrentHashMap<Channel, String>();
public static final String CLASSBRAND_HEATBEAT = "ClassBrand_HeartBeat";
@Autowired
private RestApiHub restApiHub;
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { // (1)
Channel incoming = ctx.channel();
JSONObject params = JSONObject.parseObject(msg.text()).getJSONObject("params");
String macid = channelClassBrandMap.get(incoming);
if (CLASSBRAND_HEATBEAT.equals(params.getString("type"))) {
putChannelMap(incoming, params, macid);
incoming.writeAndFlush(new TextWebSocketFrame(CLASSBRAND_HEATBEAT));
}
}
private void putChannelMap(Channel incoming, JSONObject params, String macid) {
logger.info("classBrand macid=" + params.getString("macid") + "加入");
if (StringUtil.isNullOrEmpty(macid)) {
channelClassBrandMap.put(incoming, params.getString("macid"));
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // (2)
Channel incoming = ctx.channel();
logger.info("Client:" + incoming.remoteAddress() + "加入");
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
Channel incoming = ctx.channel();
logger.info("Client:" + incoming.remoteAddress() + "离开");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
Channel incoming = ctx.channel();
logger.info("Client:" + incoming.remoteAddress() + "在线");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
Channel incoming = ctx.channel();
channelClassBrandMap.remove(incoming);
System.out.println("Client:" + incoming.remoteAddress() + "掉线");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) // (7)
throws Exception {
Channel incoming = ctx.channel();
logger.info("Client:" + incoming.remoteAddress() + "异常");
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
}
public static Channel getChannelByMacid(String macid) {
for (Map.Entry<Channel, String> entry : channelClassBrandMap.entrySet()) {
if (entry.getValue().equals(macid)) {
return entry.getKey();
}
}
return null;
}
public static List<String> listClassBrandState(List<String> macids) {
Set<String> onlineClassBrandSet = channelClassBrandMap.values().stream().collect(Collectors.toSet());
return macids.stream().filter(macid -> makeClassBrandState(macid, onlineClassBrandSet))
.collect(Collectors.toList());
}
private static Boolean makeClassBrandState(String macid, Set<String> onlineClassBrandSet) {
if (onlineClassBrandSet.contains(macid)) {
return true;
}
return false;
}
}
package com.spacetech.websocketchat.ClassbrandWebsocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Websocket 聊天服务器-服务端
*
* @author waylau.com
* @date 2015-3-7
*/
public class WebsocketClassBrandServer {
private static Logger logger = LoggerFactory.getLogger(WebsocketClassBrandServer.class);
private int port;
public WebsocketClassBrandServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
.childHandler(new WebsocketClassBrandServerInitializer()) // (4)
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
logger.info("WebsocketClassBrandServer 启动了" + port);
// 绑定端口,开始接收进来的连接
b.bind(port).sync(); // (7)
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 9000;
}
new WebsocketClassBrandServer(port).run();
}
}
\ No newline at end of file
package com.spacetech.websocketchat.ClassbrandWebsocket;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
/**
* 服务端 ChannelInitializer
*
* @author waylau.com
* @date 2015-3-13
*/
public class WebsocketClassBrandServerInitializer extends ChannelInitializer<SocketChannel> { // 1
@Override
public void initChannel(SocketChannel ch) throws Exception {// 2
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(64 * 1024));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new WebSocketServerProtocolHandler("/weixtclassbrand"));
pipeline.addLast(new TextWebSocketClassBrandFrameHandler());
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment