一些基础类

最初步骤

public static void boot(Class<?> clazz, String[] args) {
assignRandomPort();
CoreBoot.application = new DmcApplication(clazz);
ArgsProperty simpleCommandLinePropertySource = new ArgsProperty(args);
CoreBoot.run = CoreBoot.application.run(simpleCommandLinePropertySource);
setConfig();
// CoreBoot.bootLocalConfig();
}

 

public void boot(){

public static DmcApplication application;
public static DmcApplicationContext run;

}

 

package com.game2sky.publib.framework.app;

import com.game2sky.publib.framework.common.log.DmcLog;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.config.ConfigurationSource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
DmcApplication 
* @version 0.1
**/
public class DmcApplication {
public static final String DEFAULT_CONTEXT_CLASS = "com.game2sky.publib.util.AMApplicationContext";
private static final int BUF_SIZE = 16384;

// 文件是否是绝对路径
public static boolean isFileAbsolutePath = false;
public static String fileAbsolutePath;


private void parseResourceFileAbsolutePath(ArgsProperty commandLinePropertySource) {
DmcApplication.fileAbsolutePath = commandLinePropertySource.getProperty("resource");
DmcApplication.isFileAbsolutePath = !com.game2sky.publib.framework.util.StringUtils.isEmpty(DmcApplication.fileAbsolutePath);
if (DmcApplication.isFileAbsolutePath) {
System.out.println("resource.absolute.path - " + DmcApplication.fileAbsolutePath);
}
}

public DmcApplication(Object... sources) {
}

public DmcApplicationContext run(ArgsProperty simpleCommandLinePropertySource) {
DmcApplicationContext context = null;
try {
parseResourceFileAbsolutePath(simpleCommandLinePropertySource);
context = createApplicationContext(simpleCommandLinePropertySource);
//banner
printBanner(context);
} catch (Exception e) {
e.printStackTrace();
}
return context;
}

private void printBanner(DmcApplicationContext context) {
String configStr = context.getEnvironment().getProperty("banner.location");
if(!StringUtils.isEmpty(configStr)) {
try {
URL url = context.getURL(configStr);
ConfigurationSource source = context.getConfigurationSource(url);
DmcLog.LOG_COMMON.info(new String(toByteArray(source.getInputStream())));
}catch(Exception e) {
e.printStackTrace();
}
}

}

protected DmcApplicationContext createApplicationContext(ArgsProperty simpleCommandLinePropertySource) throws Exception {
DmcApplicationContext context = new DmcApplicationContext(simpleCommandLinePropertySource);

return context;
}

protected static byte[] toByteArray(final InputStream is) throws IOException {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
final byte[] data = new byte[BUF_SIZE];

while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}

return buffer.toByteArray();
}

}

****************************************************************

package com.game2sky.publib.framework.app;

import com.game2sky.publib.communication.ADataModel;
import com.game2sky.publib.framework.common.log.DmcLog;
import com.game2sky.publib.framework.util.FileUtils;
import com.game2sky.publib.framework.util.ScanUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
DmcApplicationContext
* @version 0.1
**/
public class DmcApplicationContext {
// 容器对象 key:class ,value类
private static ConcurrentHashMap<String, Object> aDataModelBeans = new ConcurrentHashMap<>();

private static ConcurrentHashMap<String, Object> aMControllerBeans = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, Object> aMComponentBeans = new ConcurrentHashMap<>();

private static Set<String> beanDefinitionNames = new HashSet<>();
private static ConcurrentHashMap<String, Object> allBeans = new ConcurrentHashMap<>();

private static DmcConfigurableEnvironment environment;

/**
* The name of the Spring property that contains a reference to the logging
* configuration to load.
*/
public static final String CONFIG_PROPERTY = "logging.config";
/**
* Pseudo URL prefix for loading from the class path: "classpath:"
*/
public static final String CLASSPATH_URL_PREFIX = "classpath:";
/**
* URL prefix for loading from the file system: "file:"
*/
public static final String FILE_URL_PREFIX = "file:";
/**
* URL prefix for loading from a jar file: "jar:"
*/
public static final String JAR_URL_PREFIX = "jar:";
private static final String FILE_PROTOCOL = "file";

public DmcApplicationContext(ArgsProperty simpleCommandLinePropertySource) throws Exception {
environment = new DmcConfigurableEnvironment(simpleCommandLinePropertySource);
//spring 的log4j也是在 Context时初始化的
String logConfig = environment.getProperty(CONFIG_PROPERTY);
// String location = logConfig.substring(CLASSPATH_URL_PREFIX.length());
if (!StringUtils.isEmpty(logConfig)) {
LoggerContext ctx = getLoggerContext();
URL url = getURL(logConfig);
// ConfigurationSource source = getConfigurationSource(url);
// ctx.start(ConfigurationFactory.getInstance().getConfiguration(source));
//
// ctx.getConfiguration();
ctx.setConfigLocation(url.toURI());
ctx.reconfigure();


Logger logger = LoggerFactory.getLogger(DmcApplicationContext.class);
logger.getName();
}
}

public static void initBeans() throws Exception {
Set<Class<?>> listClass = ScanUtil.getClasses("com.game2sky");
for (Class<?> classInfo : listClass) {
//非announce类不处理
if (classInfo.getAnnotations() == null
|| classInfo.getAnnotations().length < 1) {
continue;
}

if (classInfo.isInterface() || classInfo.getConstructors().length < 1) {
continue;
}

//ADataModel
ADataModel type = classInfo.getDeclaredAnnotation(ADataModel.class);
if (type != null) {
Object bean = classInfo.newInstance();
aDataModelBeans.put(classInfo.toString(), bean);
recordBeans(classInfo, bean);
}

//AMComponent
if (!dealComponet(classInfo, DmcComponent.class)) {
dealComponet(classInfo, DmcController.class);
}
}

}

private static boolean dealComponet(Class<?> classInfo, Class AnnotationClass) throws Exception {
//DmcComponent
if (classInfo.getDeclaredAnnotation(AnnotationClass) != null) {
Object bean = classInfo.newInstance();
aMComponentBeans.put(classInfo.toString(), bean);
recordBeans(classInfo, bean);

return true;

}
return false;
}

private static void recordBeans(Class<?> classInfo, Object bean) {
String className = classInfo.toString();
allBeans.put(className, bean);
beanDefinitionNames.add(className);
}

public static ConcurrentHashMap<String, Object> getADataModelBeans() {
return aDataModelBeans;
}

public static ConcurrentHashMap<String, Object> getAMControllerBeans(){
return aMControllerBeans;
}
public Map<String, Object> getBeansWithAnnotation(Class clazz) {
Map<String, Object> rtn = new HashMap<>();
Iterator<Object> itor = allBeans.values().iterator();
while(itor.hasNext()) {
Object bean = itor.next();
if(bean.getClass().getAnnotation(clazz) != null) {
rtn.put(bean.getClass().toString(), bean);
}
}

return rtn;
}

public Class getType(String className) {
if(allBeans.containsKey(className)) {
Object bean = allBeans.get(className);
return bean.getClass();
}

return null;
}

public DmcConfigurableEnvironment getEnvironment() {
return environment;
}

public void close() {
DmcHttpServer.close();
}

public Set<String> getBeanDefinitionNames() {
return beanDefinitionNames;
}


public <T> Map<String, T> getBeansOfType(Class<T> type) {
Map<String, T> rtn = new HashMap<>();
// Check all bean definitions.s
for (String beanName : this.beanDefinitionNames) {
if (allBeans.containsKey(beanName)) {
Object bean = allBeans.get(beanName);

if (type.isInstance(bean)) {
rtn.put(beanName, (T) bean);
}
}
}
return rtn;
}

public static ConfigurationSource getConfigurationSource(URL url) throws IOException {
InputStream stream = url.openStream();
if (FILE_PROTOCOL.equals(url.getProtocol())) {
return new ConfigurationSource(stream, getFile(url));
}
return new ConfigurationSource(stream, url);
}

public static URL getURL(String resourceLocation) throws FileNotFoundException {
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String logPath = DmcApplication.isFileAbsolutePath ? DmcApplication.fileAbsolutePath + File.separator + path : path;
URL url;
if (DmcApplication.isFileAbsolutePath) {
url = FileUtils.absolutePathToURL(logPath);
} else {
url = (cl != null ? cl.getResource(logPath) : ClassLoader.getSystemResource(logPath));
}
DmcLog.LOG_STDOUT.info("properties.path - " + path);
if (url == null) {
String description = "class path resource [" + path + "]";
throw new FileNotFoundException(description +
" cannot be resolved to URL because it does not exist");
}
return url;
}
try {
// try URL
return new URL(resourceLocation);
} catch (MalformedURLException ex) {
// no URL -> treat as file path
try {
return new File(resourceLocation).toURI().toURL();
} catch (MalformedURLException ex2) {
throw new FileNotFoundException("Resource location [" + resourceLocation +
"] is neither a URL not a well-formed file path");
}
}
}

private LoggerContext getLoggerContext() {
return (LoggerContext) LogManager.getContext(false);
}

public static File getFile(URL resourceUrl) throws FileNotFoundException {
try {
return new File(toURI(resourceUrl.toString()).getSchemeSpecificPart());
} catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new File(resourceUrl.getFile());
}
}

public static URI toURI(String location) throws URISyntaxException {
return new URI(StringUtils.replace(location, " ", "%20"));
}

}

 

***********************************************************

 

package com.game2sky.publib.framework.app;

import java.util.Properties;

/**
ArgsProperty 
* @date 创建时间:2019年3月12日 下午3:31:43
**/
public class ArgsProperty {
public static final String PARAM = "=";

private Properties props = new Properties();

public ArgsProperty(String[] args) {
if (args != null) {
for (String s : args) {
if (s.contains(PARAM)) {
String key = s.substring(s.indexOf("--") + 2, s.indexOf(PARAM));
String value = s.substring(s.indexOf(PARAM) + 1, s.length());

props.setProperty(key, value);
}
}
}
}

public String getProperty(String key) {
return props.getProperty(key);
}

}

 

 

*********************************************************

 

package com.game2sky.publib.framework.app;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import org.apache.commons.lang.ClassUtils;

/**
* 启动辅助类
* @date 2019-03-07
*/

public class DmcApplicationHome {
private final File source;

public DmcApplicationHome(Class<?> sourceClass) {
this.source = findSource(sourceClass == null ? getStartClass() : sourceClass);
}

/**
* Returns the underlying source used to find the home directory. This is usually the
* jar file or a directory. Can return {@code null} if the source cannot be
* determined.
* @return the underlying source or {@code null}
*/
public File getSource() {
return this.source;
}

private Class<?> getStartClass() {
try {
ClassLoader classLoader = getClass().getClassLoader();
return getStartClass(classLoader.getResources("META-INF/MANIFEST.MF"));
}
catch (Exception ex) {
return null;
}
}

private File findSource(Class<?> sourceClass) {
try {
ProtectionDomain domain = (sourceClass == null ? null
: sourceClass.getProtectionDomain());
CodeSource codeSource = (domain == null ? null : domain.getCodeSource());
URL location = (codeSource == null ? null : codeSource.getLocation());
File source = (location == null ? null : findSource(location));
if (source != null && source.exists() && !isUnitTest()) {
return source.getAbsoluteFile();
}
return null;
}
catch (Exception ex) {
return null;
}
}

private File findSource(URL location) throws IOException {
URLConnection connection = location.openConnection();
if (connection instanceof JarURLConnection) {
return getRootJarFile(((JarURLConnection) connection).getJarFile());
}
return new File(location.getPath());
}

private File getRootJarFile(JarFile jarFile) {
String name = jarFile.getName();
int separator = name.indexOf("!/");
if (separator > 0) {
name = name.substring(0, separator);
}
return new File(name);
}

private boolean isUnitTest() {
try {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getClassName().startsWith("org.junit.")) {
return true;
}
}
}
catch (Exception ex) {
}
return false;
}

private Class<?> getStartClass(Enumeration<URL> manifestResources) {
while (manifestResources.hasMoreElements()) {
try {
InputStream inputStream = manifestResources.nextElement().openStream();
try {
Manifest manifest = new Manifest(inputStream);
String startClass = manifest.getMainAttributes()
.getValue("Start-Class");
if (startClass != null) {
return ClassUtils.getClass(getClass().getClassLoader(),
startClass);
}
}
finally {
inputStream.close();
}
}
catch (Exception ex) {
}
}
return null;
}
}

 

**************************************************************

 

package com.game2sky.publib.framework.app;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


/**
* @author final
* @date 创建时间:2019年3月7日 下午7:51:16
* @version 0.1
**/
public class DmcClassUtil {

/**
* 取得某个接口下所有实现这个接口的类
*/
public static List<Class> getAllClassByInterface(Class c) {
List<Class> returnClassList = null;

if (c.isInterface()) {
// 获取当前的包名
String packageName = c.getPackage().getName();
// 获取当前包下以及子包下所以的类
List<Class<?>> allClass = getClasses(packageName);
if (allClass != null) {
returnClassList = new ArrayList<Class>();
for (Class classes : allClass) {
// 判断是否是同一个接口
if (c.isAssignableFrom(classes)) {
// 本身不加入进去
if (!c.equals(classes)) {
returnClassList.add(classes);
}
}
}
}
}

return returnClassList;
}

/*
* 取得某一类所在包的所有类名 不含迭代
*/
public static String[] getPackageAllClassName(String classLocation, String packageName) {
// 将packageName分解
String[] packagePathSplit = packageName.split("[.]");
String realClassLocation = classLocation;
int packageLength = packagePathSplit.length;
for (int i = 0; i < packageLength; i++) {
realClassLocation = realClassLocation + File.separator + packagePathSplit[i];
}
File packeageDir = new File(realClassLocation);
if (packeageDir.isDirectory()) {
String[] allClassName = packeageDir.list();
return allClassName;
}
return null;
}

/**
* 从包package中获取所有的Class
*
* @param pack
* @return
*/
public static List<Class<?>> getClasses(String packageName) {

// 第一个class类的集合
List<Class<?>> classes = new ArrayList<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}

return classes;
}

/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
List<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Class.forName(packageName + '.' + className));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

// 首字母转小写
public static String toLowerCaseFirstOne(String s) {
if (Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}

// 初始化对象
public static Object newInstance(Class<?> classInfo)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return classInfo.newInstance();
}

}

 

 

**************************************************************

 

package com.game2sky.publib.framework.boot;

import com.game2sky.prilib.communication.PrivPSEnum;
import com.game2sky.publib.communication.ADataModel;
import com.game2sky.publib.communication.IPSEnum;
import com.game2sky.publib.communication.PSEnum;
import com.game2sky.publib.communication.SerializationUtil;
import com.game2sky.publib.communication.common.ErrorMessage;
import com.game2sky.publib.framework.app.*;
import com.game2sky.publib.framework.common.log.DmcLog;
import com.game2sky.publib.framework.common.properties.DmcConf;
import com.game2sky.publib.framework.common.properties.DmcConst;
import com.game2sky.publib.framework.communication.Message;
import com.game2sky.publib.framework.dbs.model.DBSConnectInfo;
import com.game2sky.publib.framework.netty.support.DmcAttributeKey;
import com.game2sky.publib.framework.protostuf.OperationDefine;
import com.game2sky.publib.framework.protostuf.ProtoBufInvokeMethod;
import com.game2sky.publib.framework.protostuf.ProtoStuffMapping;
import com.game2sky.publib.framework.util.FileUtils;
import com.game2sky.publib.framework.util.StringUtils;
import com.google.common.collect.Maps;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* 启动基类
*
* @author amyn
* @version v0.1 2017年3月10日 下午2:29:42 amyn
*/
public class DmcFrameWorkBoot {
/** 实时更新的配置文件 */
public static DmcConf conf;
/** 多语言配置,当前只有个别使用*/
private static Properties i18n;
/** 进程名字*/
public static String AppName;
/** 本进程类型,benfu,kuafu,quanfu */
public static ServerTypeEnum SELF_SERVER_TYPE;
/** 本进程对外提供服务的IP地址 */
public static String SELF_IP;
/** 本进程对外提供服务的IP地址 */
public static String IN_IP;
/** 本进程对外提供服务的IP地址 */
public static String OUT_IP;
/** 本进程对外提供服务的端口 */
public static int SELF_PORT;
/** 战斗服提供服务的端口 */
public static int BATTLE_PORT;
/** 本进程对外提供服务的标识 */
public static String SELF_FLAG;
/**本进程的启动时间*/
public static long SERVER_START_TIME;
/** 服务器是否已经完全启动*/
public volatile static boolean START_SUCCESS = false;
/** 通讯协议定义 */
public static final Map<Object, OperationDefine> OP_DEFINE_MAP = new HashMap<Object, OperationDefine>();
/** 路由 */
public static final Map<Class<?>, ProtoBufInvokeMethod> INVOKE_METHOD_MAP = new HashMap<Class<?>, ProtoBufInvokeMethod>();
/** 直连DB配置。 */
public static final Map<String, DBSConnectInfo> DB_INFO = new HashMap<String, DBSConnectInfo>();
/** 跨服信息 serverId, kuafuSceneFlag*/
public static final Map<Integer, String> KUA_FU_SERVER_ID_MAP = new HashMap<Integer, String>();
/** version版本相关信息 */
public static final Map<String, String> versionMap = Maps.newHashMap();

public static DmcApplication application;
public static DmcApplicationContext run;

// /**
// * 本进程内逻辑合服的多个本服信息
// */
// public static List<Integer> serverIdList = new ArrayList<Integer>();

/**
* 启动Spring
*
* @param clazz
* @param simpleCommandLinePropertySource
*/
public static void bootSpring(Class<?> clazz, ArgsProperty simpleCommandLinePropertySource) {
DmcLog.LOG_STDOUT.info("init.spring...");
application = new DmcApplication(clazz);
run = application.run(simpleCommandLinePropertySource);
}

/**
* 初始化协议等数据
*/
public static void initData() {
FileInputStream fileInputStream = null;
try {
boolean isFileAbsolutePath = DmcApplication.isFileAbsolutePath;
String fileAbsolutePath = DmcApplication.fileAbsolutePath;
String i18nPath = isFileAbsolutePath ? fileAbsolutePath + File.separator + "i18n.properties" : "i18n.properties";
URL resource;
if (DmcApplication.isFileAbsolutePath) {
resource = FileUtils.absolutePathToURL(i18nPath);
} else {
resource = DmcFrameWorkBoot.class.getClassLoader().getResource(i18nPath);
}
DmcLog.LOG_STDOUT.info("i18n.properties.path - " + i18nPath);
fileInputStream = new FileInputStream(resource.getPath());
Properties properties = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, DmcConst.UTF8);
properties.load(inputStreamReader);
i18n = properties;
} catch (IOException e) {
DmcLog.LOG_STDOUT.error("", e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
}
initOperationDefine();
getAppName();
if (DmcApplication.isFileAbsolutePath) {
readVersion(DmcApplication.fileAbsolutePath + File.separator + "version.txt", true);
} else {
readVersion("version.txt", false);
}
}

public static void initOperationDefine() {
PSEnum[] values = PSEnum.values();
for (int i = 0; i < values.length; i++) {
PSEnum ps = values[i];
if (ps == PSEnum.PSEnum_NULL || ps == PSEnum.SUPERSDK_RECHARGE) {
continue;
}
int value = ps.getCode();
Class<?> type = ps.getClazz();

if (DmcFrameWorkBoot.OP_DEFINE_MAP.containsKey(value)) {
DmcLog.LOG_STDOUT.error("repeated PSEnum code " //
+ "[code:" + value + ", " //
+ "old.class:" + DmcFrameWorkBoot.OP_DEFINE_MAP.get(value).clazz().toString() //
+ " new.class:" + type.toString() + "]");
System.exit(1);
}
if (DmcFrameWorkBoot.OP_DEFINE_MAP.containsKey(type)) {
DmcLog.LOG_STDOUT.error("repeated PSEnum class " //
+ "[code:" + value + ", " //
+ "old.code:" + DmcFrameWorkBoot.OP_DEFINE_MAP.get(type).code() //
+ " new.code:" + value + "]");
System.exit(1);
}

OperationDefine operationDefine = new OperationDefine(ps);
DmcFrameWorkBoot.OP_DEFINE_MAP.put(value, operationDefine);
DmcFrameWorkBoot.OP_DEFINE_MAP.put(type, operationDefine);

SerializationUtil.initSchema(type);
DmcLog.LOG_STDOUT.debug("find PS " + operationDefine.toString());
}

PrivPSEnum[] pvalues = PrivPSEnum.values();
for (int i = 0; i < pvalues.length; i++) {
PrivPSEnum ps = pvalues[i];
if (ps == PrivPSEnum.PrivPSEnum_NULL) {
continue;
}
int value = ps.getCode();
Class<?> type = ps.getClazz();

if (DmcFrameWorkBoot.OP_DEFINE_MAP.containsKey(value)) {
DmcLog.LOG_STDOUT.error("repeated PrivPSEnum code " //
+ "[code:" + value + ", " //
+ "old.class:" + DmcFrameWorkBoot.OP_DEFINE_MAP.get(value).clazz().toString() //
+ " new.class:" + type.toString() + "]");
System.exit(1);
}
if (DmcFrameWorkBoot.OP_DEFINE_MAP.containsKey(type)) {
DmcLog.LOG_STDOUT.error("repeated PrivPSEnum class " //
+ "[code:" + value + ", " //
+ "old.code:" + DmcFrameWorkBoot.OP_DEFINE_MAP.get(type).code() //
+ " new.code:" + value + "]");
System.exit(1);
}

OperationDefine opDefine = new OperationDefine(ps);
DmcFrameWorkBoot.OP_DEFINE_MAP.put(value, opDefine);
DmcFrameWorkBoot.OP_DEFINE_MAP.put(type, opDefine);

SerializationUtil.initSchema(type);
DmcLog.LOG_STDOUT.debug("find PrivPS " + opDefine.toString());
}

Map<String, Object> aDataModels = DmcFrameWorkBoot.run.getBeansWithAnnotation(ADataModel.class);
for (Map.Entry<String, Object> entry : aDataModels.entrySet()) {
String key = entry.getKey();
Class<?> type = DmcFrameWorkBoot.run.getType(key);
SerializationUtil.initSchema(type);
}

// Map<String, Object> controllers = DmcFrameWorkBoot.run.getAMControllerBeans();
Map<String, Object> controllers = DmcFrameWorkBoot.run.getBeansWithAnnotation(DmcController.class);
for (Map.Entry<String, Object> entry : controllers.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
Class<?> type = DmcFrameWorkBoot.run.getType(key);
Method[] methods = type.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
ProtoStuffMapping annotation = method.getAnnotation(ProtoStuffMapping.class);
if (annotation != null) {
IPSEnum ps = annotation.value();
if (ps == PSEnum.PSEnum_NULL) {
ps = annotation.pvalue();
}
ProtoBufInvokeMethod protoBufInvokeMethod = new ProtoBufInvokeMethod(value, method);
ProtoBufInvokeMethod protoBufInvokeMethod2 = DmcFrameWorkBoot.INVOKE_METHOD_MAP.get(ps.getClazz());
if (protoBufInvokeMethod2 != null) {
DmcLog.LOG_STDOUT.error("repeated ProtoBufMapping PSEnum [code:" + value + ", " //
+ "old:" + protoBufInvokeMethod2.getMethod().toGenericString() //
+ " new.code:" + method.toGenericString() + "]");
System.exit(1);
}
DmcFrameWorkBoot.INVOKE_METHOD_MAP.put(ps.getClazz(), protoBufInvokeMethod);
DmcLog.LOG_STDOUT.debug("find ProtoBufMapping [" + ps.toString() + "], [" + method.toGenericString()
+ "]");
}
}
}
}

public static String i18n(String key) {
return i18n.getProperty(key);
}

public static void readVersion(String versionFilePath, boolean isAbsolute) {
URL confResource = null;
BufferedReader bufferedReader = null;
try {
if (isAbsolute) {
confResource = FileUtils.absolutePathToURL(versionFilePath);
} else {
confResource = DmcFrameWorkBoot.class.getClassLoader().getResource(versionFilePath);
}
if (confResource == null) {
DmcLog.LOG_ERROR.error(versionFilePath + " not exist");
return;
}
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(confResource.getPath())), "UTF8"));
// 以目前的格式只读第一行即可
String line = null;
while ((line = bufferedReader.readLine()) != null) {
int splitIndex = line.indexOf(":");
if (splitIndex == -1) {
continue;
}
String k = line.substring(0, splitIndex);
String v = line.substring(splitIndex + 1, line.length());
if (StringUtils.isEmpty(k) || StringUtils.isEmpty(v)) {
continue;
}
versionMap.put(k.trim(), v.trim());
}
} catch (Exception e) {
DmcLog.LOG_ERROR.error("", e);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static String getCatType() {
if (AppName == null) {
AppName = getAppName() + "." + Thread.currentThread().getThreadGroup().getName();
}
return AppName;
}

public static String getAppName() {
return getEnvironment().getProperty("info.app.name");
}

public static DmcConfigurableEnvironment getEnvironment() {
return run.getEnvironment();
}

public static boolean isBenFu() {
return SELF_SERVER_TYPE == ServerTypeEnum.BENFU;
}

public static boolean isKuaFu() {
return SELF_SERVER_TYPE == ServerTypeEnum.KUAFU;
}

public static boolean isQuanFu() {
return SELF_SERVER_TYPE == ServerTypeEnum.QUANFU;
}

public static boolean isBattle() {
return SELF_SERVER_TYPE == ServerTypeEnum.BATTLE;
}

public static boolean isObserver() {
return SELF_SERVER_TYPE == ServerTypeEnum.OBSERVER;
}

/**
*
* 服务端强制关闭连接前,先给客户端推送一条原因消息
* @param channel
* @param msg
* @param log
*/
public static void closeChannel(final Channel channel,int serverId,long playerId,String msg, int errorType,final String log) {
closeChannel(channel, Message.buildByServerId(playerId, serverId, new ErrorMessage(0, msg, 0, errorType, false)), log);
}

/**
*
* 服务端强制关闭连接前,先给客户端推送一条原因消息
* @param channel
* @param msg
* @param errorType
* @param log
*/
public static void closeChannel(final Channel channel, String msg, int errorType, final String log) {
closeChannel(channel, Message.buildByServerId(0L, 0, new ErrorMessage(0, msg, 0, errorType, false)), log);
}

/**
* 服务端强制关闭连接前,先给客户端推送一条原因消息
* @param channel
* @param message
* @param log
*/
public static void closeChannel(final Channel channel, Message message, final String log) {
Long playerId = channel.attr(DmcAttributeKey.PLAYER_ID).get();
channel.attr(DmcAttributeKey.CLOSED_REASION).set(log);
if (message != null) {
channel.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE);
}else {
channel.close();
}
DmcLog.LOG_STDOUT.info(String.format("player Id :%s closeChannel: %s, the reason is : %s .", playerId, channel, log));
}

/**
* 服务端强制关闭channel
*
* @param channel
* @param reasion 原因
*/
public static void closeChannel(final Channel channel, String reasion) {
closeChannel(channel, null, reasion);
}

}

 

******************************************************************

 

package com.game2sky.publib.framework.common.properties;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;

import com.game2sky.publib.framework.common.log.DmcLog;

public class DmcProperties extends FileWatchdog {

protected Properties properties;

private Map<String, Object> tmpMap = new ConcurrentHashMap<String, Object>();

public DmcProperties(String filename) {
super(filename);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filename);
properties = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, DmcConst.UTF8);
properties.load(inputStreamReader);
delay = 1000;
start();
} catch (IOException e) {
DmcLog.LOG_ERROR.error("", e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
}
}

@Override
protected void doOnChange() {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filename);
Properties properties = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, DmcConst.UTF8);
properties.load(inputStreamReader);
this.properties = properties;
if (tmpMap != null) {
tmpMap.clear();
}
} catch (IOException e) {
DmcLog.LOG_ERROR.error("", e);
DmcLog.fatal("confHotUpdate:热更[{}]失败", filename);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
}
}

public String getString(String key) {
return properties.getProperty(key);
}

public StringBuilder getStringBuilder(String key) {
return new StringBuilder(properties.getProperty(key));
}

public String getString(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}

public Integer getInteger(String key) {
Object object = tmpMap.get(key);
if (object == null) {
object = Integer.valueOf(getString(key));
tmpMap.put(key, object);
}
return (Integer) object;
}

public Integer getInteger(String key, Integer defaultValue) {
Object object = tmpMap.get(key);
if (object == null) {
object = Integer.valueOf(getString(key, String.valueOf(defaultValue)));
tmpMap.put(key, object);
}
return (Integer)object;
}

public Boolean getBoolean(String key) {
Object object = tmpMap.get(key);
if (object == null) {
object = Boolean.valueOf(getString(key));
tmpMap.put(key, object);
}
return (Boolean)object;
}

public Boolean getBoolean(String key, Boolean defaultValue) {
Object object = tmpMap.get(key);
if (object == null) {
object = Boolean.valueOf(getString(key, String.valueOf(defaultValue)));
tmpMap.put(key, object);
}
return (Boolean)object;
}

@SuppressWarnings("unchecked")
public Set<String> getStringSet(String key) {

Object object = tmpMap.get(key);
if (object == null) {
String string = getString(key);
Set<String> set = new HashSet<String>();
String[] split = StringUtils.split(string, DmcConst.SEPARATOR_CHARS_COLON);
for (int i = 0; i < split.length; i++) {
String[] split2 = StringUtils.split(split[i], DmcConst.SEPARATOR_CHARS_COMMA);
for (int j = 0; j < split2.length; j++) {
String[] split3 = StringUtils.split(split2[j], DmcConst.SEPARATOR_CHARS_SEMICOLON);
set.addAll(Arrays.asList(split3));
}
}
object = set;
tmpMap.put(key, object);
}


return (Set<String>)object;
}

@SuppressWarnings("unchecked")
public Set<String> getStringSet(String key, String defaultValue) {

Object object = tmpMap.get(key);
if (object == null) {
String string = getString(key, defaultValue);
Set<String> set = new HashSet<String>();
String[] split = StringUtils.split(string, DmcConst.SEPARATOR_CHARS_COLON);
for (int i = 0; i < split.length; i++) {
String[] split2 = StringUtils.split(split[i], DmcConst.SEPARATOR_CHARS_COMMA);
for (int j = 0; j < split2.length; j++) {
String[] split3 = StringUtils.split(split2[j], DmcConst.SEPARATOR_CHARS_SEMICOLON);
set.addAll(Arrays.asList(split3));
}
}
object = set;
tmpMap.put(key, object);
}


return (Set<String>)object;
}

@SuppressWarnings("unchecked")
public Set<Integer> getIntegerSet(String key) {

Object object = tmpMap.get(key);
if (object == null) {
String string = getString(key);
Set<Integer> set = new HashSet<Integer>();
String[] split = StringUtils.split(string, DmcConst.SEPARATOR_CHARS_COLON);
for (int i = 0; i < split.length; i++) {
String[] split2 = StringUtils.split(split[i], DmcConst.SEPARATOR_CHARS_COMMA);
for (int j = 0; j < split2.length; j++) {
String[] split3 = StringUtils.split(split2[j], DmcConst.SEPARATOR_CHARS_SEMICOLON);
for (int k = 0; k < split3.length; k++) {
set.add(Integer.valueOf(split3[k]));
}
}
}
object = set;
tmpMap.put(key, object);
}

return (Set<Integer>) object;
}

@SuppressWarnings("unchecked")
public Set<Integer> getIntegerSet(String key, String defaultValue) {

Object object = tmpMap.get(key);
if (object == null) {
String string = getString(key, defaultValue);
Set<Integer> set = new HashSet<Integer>();
String[] split = StringUtils.split(string, DmcConst.SEPARATOR_CHARS_COLON);
for (int i = 0; i < split.length; i++) {
String[] split2 = StringUtils.split(split[i], DmcConst.SEPARATOR_CHARS_COMMA);
for (int j = 0; j < split2.length; j++) {
String[] split3 = StringUtils.split(split2[j], DmcConst.SEPARATOR_CHARS_SEMICOLON);
for (int k = 0; k < split3.length; k++) {
set.add(Integer.valueOf(split3[k]));
}
}
}
object = set;
tmpMap.put(key, object);
}

return (Set<Integer>) object;
}

}

 

 

*************************************************************

 

 

package com.game2sky.publib.framework.common.properties;

import java.io.File;

import org.apache.log4j.helpers.LogLog;

public abstract class FileWatchdog extends Thread {

static final public long DEFAULT_DELAY = 60000;
protected String filename;

protected long delay = DEFAULT_DELAY;

File file;
long lastModif = 0;
boolean warnedAlready = false;
boolean interrupted = false;

protected FileWatchdog(String filename) {
super("FileWatchdog");
this.filename = filename;
file = new File(filename);
setDaemon(true);
checkAndConfigure();
}

public void setDelay(long delay) {
this.delay = delay;
}

abstract protected void doOnChange();

protected void checkAndConfigure() {
boolean fileExists;
try {
fileExists = file.exists();
} catch (SecurityException e) {
LogLog.warn("Was not allowed to read check file existance, file:[" + filename + "].");
interrupted = true; // there is no point in continuing
return;
}

if (fileExists) {
long l = file.lastModified(); // this can also throw a
// SecurityException
if (l > lastModif) { // however, if we reached this point this
lastModif = l; // is very unlikely.
doOnChange();
warnedAlready = false;
}
} else {
if (!warnedAlready) {
LogLog.debug("[" + filename + "] does not exist.");
warnedAlready = true;
}
}
}

public void run() {
while (!interrupted) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
checkAndConfigure();
}
}
}

 

*************************************************************

 

 

 

package com.game2sky.publib.framework.app;

import com.game2sky.publib.framework.common.log.DmcLog;
import com.game2sky.publib.framework.util.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
配置文件环境变量
**/
public class DmcConfigurableEnvironment {

public static final String APPLICATION_DIR = "application";
public static final String CONF_DIR = "conf";
public static final String PROPERTIES = ".properties";
public static final String APPLICATION_PROPERTIES = APPLICATION_DIR + "/application.properties";

private String[] activeProfiles = new String[1];

private static Properties properties = new Properties();

public DmcConfigurableEnvironment(ArgsProperty simpleCommandLinePropertySource) {
try {
init(simpleCommandLinePropertySource);
} catch (Exception e) {
e.printStackTrace();
}
}

private void init(ArgsProperty commandLinePropertySource) throws Exception {
//step1 环境的读取:先读取默认application.properties中的active值
Properties tmp = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream in = null;
try {
if (DmcApplication.isFileAbsolutePath) {
in = new FileInputStream(DmcApplication.fileAbsolutePath + File.separator + APPLICATION_PROPERTIES);
} else {
in = classLoader.getResourceAsStream(APPLICATION_PROPERTIES);
}
// 使用properties对象加载输入流
tmp.load(in);
} finally {
if (in != null) {
in.close();
}
}
//activeProfiles
activeProfiles[0] = tmp.getProperty("spring.profiles.active");

//step2、如果commandLinePropertySource有值则更改
if (commandLinePropertySource != null &&
commandLinePropertySource.getProperty("spring.profiles.active") != null) {
activeProfiles[0] = commandLinePropertySource.getProperty("spring.profiles.active");
}

//step3 配置读取
InputStream propIn = null;
try {
if (DmcApplication.isFileAbsolutePath) {
propIn = new FileInputStream(DmcApplication.fileAbsolutePath + File.separator + getContextProperty(APPLICATION_PROPERTIES));
} else {
propIn = classLoader.getResourceAsStream(getContextProperty(APPLICATION_PROPERTIES));
}
// 使用properties对象加载输入流
properties.load(propIn);
} finally {
if (propIn != null) {
propIn.close();
}
}
}

public URL getConfResource() {
String property = this.getProperty("conf.properties");
String confPath = DmcApplication.isFileAbsolutePath ? DmcApplication.fileAbsolutePath + File.separator + property : property;
URL confResource;
if (DmcApplication.isFileAbsolutePath) {
confResource = FileUtils.absolutePathToURL(confPath);
} else {
confResource = this.getClass().getClassLoader().getResource(confPath);
}
DmcLog.LOG_STDOUT.info("conf.properties.path - " + confPath);
return confResource;
}

public URL getRedissonResource() {
String property = this.getProperty("redission-config");
if(null == property || "".equals(property)){
return null;
}
String confPath = DmcApplication.isFileAbsolutePath ? DmcApplication.fileAbsolutePath + File.separator + property : property;
URL confResource;
if (DmcApplication.isFileAbsolutePath) {
confResource = FileUtils.absolutePathToURL(confPath);
} else {
confResource = this.getClass().getClassLoader().getResource(confPath);
}
DmcLog.LOG_STDOUT.info("redission-config.path - " + confPath);
return confResource;
}

public String getProperty(String key) {
return properties.getProperty(key);
}

@Deprecated
private String getContextProperty(String string) {
if (string.endsWith(PROPERTIES)) {
StringBuilder builder = new StringBuilder();
builder.append(string.substring(0, string.indexOf(PROPERTIES)))
.append("-").append(activeProfiles[0]).append(PROPERTIES);
return builder.toString();
}
return string;
}

public String[] getActiveProfiles() {
return activeProfiles;
}
}

posted @ 2021-09-09 10:53  小堆堆儿  阅读(65)  评论(0编辑  收藏  举报