From 8dbfcb9a67491317fa9e2f455771fbe83c303dd4 Mon Sep 17 00:00:00 2001 From: chuzhongzai Date: Sun, 18 Aug 2024 19:56:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=BB=B6=E8=BF=9F=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=EF=BC=8C=E5=85=81=E8=AE=B8=E6=B5=8B=E8=AF=95=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E6=9C=8D=E5=8A=A1=E5=99=A8=E4=B9=8B=E9=97=B4=E6=88=96?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E6=9C=8D=E5=8A=A1=E5=99=A8=E5=88=B0=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E5=85=AC=E7=BD=91ip=E7=9A=84=E5=BB=B6?= =?UTF-8?q?=E8=BF=9F=EF=BC=8C=E5=8E=BB=E9=99=A4=E6=9C=8D=E5=8A=A1=E5=99=A8?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E4=BF=A1=E6=81=AF=EF=BC=8C=E5=8D=87=E7=BA=A7?= =?UTF-8?q?springboot=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 25 +- .../MyBatisNativeConfiguration.java | 266 ++++++++++++++++++ .../WebComponentConfiguration.java | 14 +- .../lion/snss/controller/FileController.java | 7 +- .../lion/snss/controller/IndexController.java | 7 +- .../lion/snss/message/AbstractMessage.java | 1 - .../com/lion/snss/message/MessageCodec.java | 1 - .../com/lion/snss/message/PairMessage.java | 5 - .../com/lion/snss/message/StatusMessage.java | 25 -- .../service/CommunicateToMainService.java | 21 +- .../com/lion/snss/service/FileService.java | 12 +- src/main/java/com/lion/snss/util/IoUtil.java | 146 ++-------- 12 files changed, 337 insertions(+), 193 deletions(-) create mode 100644 src/main/java/com/lion/snss/configuration/MyBatisNativeConfiguration.java delete mode 100644 src/main/java/com/lion/snss/message/StatusMessage.java diff --git a/pom.xml b/pom.xml index 52fc765..e40748f 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 3.2.0 + 3.1.5 com.lion @@ -68,12 +68,6 @@ 5.8.26 - - com.github.oshi - oshi-core - 6.4.5 - - io.netty netty-all @@ -82,7 +76,7 @@ org.apache.commons commons-compress - 1.21 + 1.25.0 @@ -100,6 +94,21 @@ + + org.graalvm.buildtools + native-maven-plugin + + snss + + --gc=G1 + -H:+ReportExceptionStackTraces + --initialize-at-build-time=org.apache.commons.logging.LogFactory,org.apache.commons.logging.LogFactoryService + + + true + + + diff --git a/src/main/java/com/lion/snss/configuration/MyBatisNativeConfiguration.java b/src/main/java/com/lion/snss/configuration/MyBatisNativeConfiguration.java new file mode 100644 index 0000000..e347fc1 --- /dev/null +++ b/src/main/java/com/lion/snss/configuration/MyBatisNativeConfiguration.java @@ -0,0 +1,266 @@ +package com.lion.snss.configuration; + +import org.apache.commons.logging.LogFactory; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.SelectProvider; +import org.apache.ibatis.annotations.UpdateProvider; +import org.apache.ibatis.cache.decorators.FifoCache; +import org.apache.ibatis.cache.decorators.LruCache; +import org.apache.ibatis.cache.decorators.SoftCache; +import org.apache.ibatis.cache.decorators.WeakCache; +import org.apache.ibatis.cache.impl.PerpetualCache; +import org.apache.ibatis.javassist.util.proxy.ProxyFactory; +import org.apache.ibatis.javassist.util.proxy.RuntimeSupport; +import org.apache.ibatis.logging.Log; +import org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl; +import org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl; +import org.apache.ibatis.logging.log4j2.Log4j2Impl; +import org.apache.ibatis.logging.nologging.NoLoggingImpl; +import org.apache.ibatis.logging.slf4j.Slf4jImpl; +import org.apache.ibatis.logging.stdout.StdOutImpl; +import org.apache.ibatis.reflection.TypeParameterResolver; +import org.apache.ibatis.scripting.defaults.RawLanguageDriver; +import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.mapper.MapperFactoryBean; +import org.mybatis.spring.mapper.MapperScannerConfigurer; +import org.springframework.aot.hint.MemberCategory; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.RuntimeHintsRegistrar; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution; +import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor; +import org.springframework.beans.factory.aot.BeanRegistrationExcludeFilter; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; +import org.springframework.beans.factory.support.RegisteredBean; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportRuntimeHints; +import org.springframework.core.ResolvableType; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Configuration(proxyBeanMethods = false) +@ImportRuntimeHints(MyBatisNativeConfiguration.MyBaitsRuntimeHintsRegistrar.class) +public class MyBatisNativeConfiguration { + + @Bean + MyBatisBeanFactoryInitializationAotProcessor myBatisBeanFactoryInitializationAotProcessor() { + return new MyBatisBeanFactoryInitializationAotProcessor(); + } + + @Bean + static MyBatisMapperFactoryBeanPostProcessor myBatisMapperFactoryBeanPostProcessor() { + return new MyBatisMapperFactoryBeanPostProcessor(); + } + + static class MyBaitsRuntimeHintsRegistrar implements RuntimeHintsRegistrar { + + @Override + public void registerHints(RuntimeHints hints, ClassLoader classLoader) { + Stream.of(RawLanguageDriver.class, + XMLLanguageDriver.class, + RuntimeSupport.class, + ProxyFactory.class, + Slf4jImpl.class, + Log.class, + JakartaCommonsLoggingImpl.class, + Log4j2Impl.class, + Jdk14LoggingImpl.class, + StdOutImpl.class, + NoLoggingImpl.class, + SqlSessionFactory.class, + PerpetualCache.class, + FifoCache.class, + LruCache.class, + SoftCache.class, + WeakCache.class, + SqlSessionFactoryBean.class, + ArrayList.class, + HashMap.class, + TreeSet.class, + HashSet.class + ).forEach(x -> hints.reflection().registerType(x, MemberCategory.values())); + Stream.of( + "org/apache/ibatis/builder/xml/*.dtd", + "org/apache/ibatis/builder/xml/*.xsd" + ).forEach(hints.resources()::registerPattern); + } + } + + static class MyBatisBeanFactoryInitializationAotProcessor + implements BeanFactoryInitializationAotProcessor, BeanRegistrationExcludeFilter { + + private final Set> excludeClasses = new HashSet<>(); + + MyBatisBeanFactoryInitializationAotProcessor() { + excludeClasses.add(MapperScannerConfigurer.class); + } + + @Override public boolean isExcludedFromAotProcessing(RegisteredBean registeredBean) { + return excludeClasses.contains(registeredBean.getBeanClass()); + } + + @Override + public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) { + String[] beanNames = beanFactory.getBeanNamesForType(MapperFactoryBean.class); + if (beanNames.length == 0) { + return null; + } + return (context, code) -> { + RuntimeHints hints = context.getRuntimeHints(); + for (String beanName : beanNames) { + BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName.substring(1)); + PropertyValue mapperInterface = beanDefinition.getPropertyValues().getPropertyValue("mapperInterface"); + if (mapperInterface != null && mapperInterface.getValue() != null) { + Class mapperInterfaceType = (Class) mapperInterface.getValue(); + if (mapperInterfaceType != null) { + registerReflectionTypeIfNecessary(mapperInterfaceType, hints); + hints.proxies().registerJdkProxy(mapperInterfaceType); + hints.resources() + .registerPattern(mapperInterfaceType.getName().replace('.', '/').concat(".xml")); + registerMapperRelationships(mapperInterfaceType, hints); + } + } + } + }; + } + + private void registerMapperRelationships(Class mapperInterfaceType, RuntimeHints hints) { + Method[] methods = ReflectionUtils.getAllDeclaredMethods(mapperInterfaceType); + for (Method method : methods) { + if (method.getDeclaringClass() != Object.class) { + ReflectionUtils.makeAccessible(method); + registerSqlProviderTypes(method, hints, SelectProvider.class, SelectProvider::value, SelectProvider::type); + registerSqlProviderTypes(method, hints, InsertProvider.class, InsertProvider::value, InsertProvider::type); + registerSqlProviderTypes(method, hints, UpdateProvider.class, UpdateProvider::value, UpdateProvider::type); + registerSqlProviderTypes(method, hints, DeleteProvider.class, DeleteProvider::value, DeleteProvider::type); + Class returnType = MyBatisMapperTypeUtils.resolveReturnClass(mapperInterfaceType, method); + registerReflectionTypeIfNecessary(returnType, hints); + MyBatisMapperTypeUtils.resolveParameterClasses(mapperInterfaceType, method) + .forEach(x -> registerReflectionTypeIfNecessary(x, hints)); + } + } + } + + @SafeVarargs + private void registerSqlProviderTypes( + Method method, RuntimeHints hints, Class annotationType, Function>... providerTypeResolvers) { + for (T annotation : method.getAnnotationsByType(annotationType)) { + for (Function> providerTypeResolver : providerTypeResolvers) { + registerReflectionTypeIfNecessary(providerTypeResolver.apply(annotation), hints); + } + } + } + + private void registerReflectionTypeIfNecessary(Class type, RuntimeHints hints) { + if (!type.isPrimitive() && !type.getName().startsWith("java")) { + hints.reflection().registerType(type, MemberCategory.values()); + } + } + + } + + static class MyBatisMapperTypeUtils { + private MyBatisMapperTypeUtils() { + // NOP + } + + static Class resolveReturnClass(Class mapperInterface, Method method) { + Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface); + return typeToClass(resolvedReturnType, method.getReturnType()); + } + + static Set> resolveParameterClasses(Class mapperInterface, Method method) { + return Stream.of(TypeParameterResolver.resolveParamTypes(method, mapperInterface)) + .map(x -> typeToClass(x, x instanceof Class ? (Class) x : Object.class)).collect(Collectors.toSet()); + } + + private static Class typeToClass(Type src, Class fallback) { + Class result = null; + if (src instanceof Class) { + if (((Class) src).isArray()) { + result = ((Class) src).getComponentType(); + } else { + result = (Class) src; + } + } else if (src instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) src; + int index = (parameterizedType.getRawType() instanceof Class + && Map.class.isAssignableFrom((Class) parameterizedType.getRawType()) + && parameterizedType.getActualTypeArguments().length > 1) ? 1 : 0; + Type actualType = parameterizedType.getActualTypeArguments()[index]; + result = typeToClass(actualType, fallback); + } + if (result == null) { + result = fallback; + } + return result; + } + + } + + static class MyBatisMapperFactoryBeanPostProcessor implements MergedBeanDefinitionPostProcessor, BeanFactoryAware { + + private static final org.apache.commons.logging.Log LOG = LogFactory.getLog( + MyBatisMapperFactoryBeanPostProcessor.class); + + private static final String MAPPER_FACTORY_BEAN = "org.mybatis.spring.mapper.MapperFactoryBean"; + + private ConfigurableBeanFactory beanFactory; + + @Override + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = (ConfigurableBeanFactory) beanFactory; + } + + @Override + public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + if (ClassUtils.isPresent(MAPPER_FACTORY_BEAN, this.beanFactory.getBeanClassLoader())) { + resolveMapperFactoryBeanTypeIfNecessary(beanDefinition); + } + } + + private void resolveMapperFactoryBeanTypeIfNecessary(RootBeanDefinition beanDefinition) { + if (!beanDefinition.hasBeanClass() || !MapperFactoryBean.class.isAssignableFrom(beanDefinition.getBeanClass())) { + return; + } + if (beanDefinition.getResolvableType().hasUnresolvableGenerics()) { + Class mapperInterface = getMapperInterface(beanDefinition); + if (mapperInterface != null) { + // Exposes a generic type information to context for prevent early initializing + beanDefinition + .setTargetType(ResolvableType.forClassWithGenerics(beanDefinition.getBeanClass(), mapperInterface)); + } + } + } + + private Class getMapperInterface(RootBeanDefinition beanDefinition) { + try { + return (Class) beanDefinition.getPropertyValues().get("mapperInterface"); + } + catch (Exception e) { + LOG.debug("Fail getting mapper interface type.", e); + return null; + } + } + + } +} diff --git a/src/main/java/com/lion/snss/configuration/WebComponentConfiguration.java b/src/main/java/com/lion/snss/configuration/WebComponentConfiguration.java index d8e1697..54b0ba8 100644 --- a/src/main/java/com/lion/snss/configuration/WebComponentConfiguration.java +++ b/src/main/java/com/lion/snss/configuration/WebComponentConfiguration.java @@ -1,18 +1,28 @@ package com.lion.snss.configuration; import com.lion.snss.interceptor.Interceptor; -import jakarta.annotation.Resource; +import com.lion.snss.message.*; +import com.lion.snss.pojo.*; +import org.springframework.aot.hint.annotation.RegisterReflectionForBinding; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration +@RegisterReflectionForBinding(classes = {AbstractMessage.class, AdjustShareMessage.class, CancelShareMessage.class, CompressFileMessage.class, ConfigMessage.class, + ConnectMessage.class, DelayTestMessage.class, DynamicConfigMessage.class, ExtractFileMessage.class, FileOperateMessage.class, FileQueryMessage.class, FileResponseMessage.class, + MoveFileRequestMessage.class, MoveFileResponseMessage.class, PairMessage.class, PairResultMessage.class, ResponseMessage.class, ShareFileMessage.class, ShareFileQueryMessage.class, + TaskCancelMessage.class, TaskStatusMessage.class, UnPairMessage.class, FileNode.class, Record.class, ShareFile.class, ShareFileDownloadRecord.class, Task.class, + User.class}) public class WebComponentConfiguration implements WebMvcConfigurer { - @Resource Interceptor interceptor; + public WebComponentConfiguration(Interceptor interceptor) { + this.interceptor = interceptor; + } + @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") diff --git a/src/main/java/com/lion/snss/controller/FileController.java b/src/main/java/com/lion/snss/controller/FileController.java index 18ab9cf..afe333a 100644 --- a/src/main/java/com/lion/snss/controller/FileController.java +++ b/src/main/java/com/lion/snss/controller/FileController.java @@ -1,7 +1,6 @@ package com.lion.snss.controller; import com.lion.snss.service.FileService; -import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.*; @@ -11,9 +10,13 @@ import org.springframework.web.multipart.MultipartFile; @RequestMapping("/file") public class FileController { - @Resource +// @Resource FileService fileService; + public FileController(FileService fileService) { + this.fileService = fileService; + } + @GetMapping("/getFile/**") public void getFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String path, String sessionId){ fileService.getFile(httpRequest, httpResponse, path, sessionId); diff --git a/src/main/java/com/lion/snss/controller/IndexController.java b/src/main/java/com/lion/snss/controller/IndexController.java index 53fa942..2986103 100644 --- a/src/main/java/com/lion/snss/controller/IndexController.java +++ b/src/main/java/com/lion/snss/controller/IndexController.java @@ -1,7 +1,6 @@ package com.lion.snss.controller; import com.lion.snss.service.FileService; -import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; @@ -9,9 +8,13 @@ import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { - @Resource +// @Resource FileService fileService; + public IndexController(FileService fileService) { + this.fileService = fileService; + } + @GetMapping("/getFileByShareCode/**") public void getFileByShareCode(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String shareCode){ fileService.getFileByShareCode(httpRequest, httpResponse, shareCode); diff --git a/src/main/java/com/lion/snss/message/AbstractMessage.java b/src/main/java/com/lion/snss/message/AbstractMessage.java index f798d06..2fa6b23 100644 --- a/src/main/java/com/lion/snss/message/AbstractMessage.java +++ b/src/main/java/com/lion/snss/message/AbstractMessage.java @@ -7,7 +7,6 @@ import lombok.Data; public class AbstractMessage { public static final int FILE_QUERY_MESSAGE = 1; public static final int FILE_RESPONSE_MESSAGE = 2; - public static final int STATUS_MESSAGE = 10; public static final int MOVE_FILE_REQUEST_MESSAGE = 15; public static final int MOVE_FILE_RESPONSE_MESSAGE = 16; public static final int PAIR_MESSAGE = 20; diff --git a/src/main/java/com/lion/snss/message/MessageCodec.java b/src/main/java/com/lion/snss/message/MessageCodec.java index 325e7d1..771e804 100644 --- a/src/main/java/com/lion/snss/message/MessageCodec.java +++ b/src/main/java/com/lion/snss/message/MessageCodec.java @@ -37,7 +37,6 @@ public class MessageCodec extends ByteToMessageCodec { abstractMessage = switch (type){ case AbstractMessage.FILE_QUERY_MESSAGE -> objectMapper.readValue(bytes, FileQueryMessage.class); case AbstractMessage.FILE_RESPONSE_MESSAGE -> objectMapper.readValue(bytes, FileResponseMessage.class); - case AbstractMessage.STATUS_MESSAGE -> objectMapper.readValue(bytes, StatusMessage.class); case AbstractMessage.MOVE_FILE_REQUEST_MESSAGE -> objectMapper.readValue(bytes, MoveFileRequestMessage.class); case AbstractMessage.MOVE_FILE_RESPONSE_MESSAGE -> objectMapper.readValue(bytes, MoveFileResponseMessage.class); case AbstractMessage.PAIR_MESSAGE -> objectMapper.readValue(bytes, PairMessage.class); diff --git a/src/main/java/com/lion/snss/message/PairMessage.java b/src/main/java/com/lion/snss/message/PairMessage.java index fe6a438..cca2b0d 100644 --- a/src/main/java/com/lion/snss/message/PairMessage.java +++ b/src/main/java/com/lion/snss/message/PairMessage.java @@ -11,11 +11,6 @@ public class PairMessage extends AbstractMessage{ String domain; String reverseProxyPrefix; String hostname; - String system; - String cpuArch; - String cpuName; - int cpuCore; - int cpuThread; String storagePath; long availableSpace; } diff --git a/src/main/java/com/lion/snss/message/StatusMessage.java b/src/main/java/com/lion/snss/message/StatusMessage.java deleted file mode 100644 index add21df..0000000 --- a/src/main/java/com/lion/snss/message/StatusMessage.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.lion.snss.message; - -import lombok.Data; - -@Data -public class StatusMessage extends AbstractMessage{ - { - messageType = STATUS_MESSAGE; - } - int id; - long usedMemory; - long totalMemory; - double usedMemoryPercentage; - long usedSpace; - long totalSpace; - double usedSpacePercentage; - double[] systemLoad; - double usedCpuPercentage; - long ioRead; - long ioWrite; - long networkReceive; - long networkSend; - long systemUpTime; - long systemBootTime; -} diff --git a/src/main/java/com/lion/snss/service/CommunicateToMainService.java b/src/main/java/com/lion/snss/service/CommunicateToMainService.java index 502eca3..b96ef21 100644 --- a/src/main/java/com/lion/snss/service/CommunicateToMainService.java +++ b/src/main/java/com/lion/snss/service/CommunicateToMainService.java @@ -18,9 +18,7 @@ import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Promise; -import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; @@ -55,10 +53,10 @@ public class CommunicateToMainService { EventLoop eventLoop; - @Resource +// @Resource ShareFileMapper shareFileMapper; - @Resource +// @Resource TaskService taskService; ObjectMapper objectMapper = CustomUtil.objectMapper; @@ -81,7 +79,10 @@ public class CommunicateToMainService { ScheduledExecutorService scheduledExecutorService; - public CommunicateToMainService(CustomConfigurationMapper customConfigurationMapper, Interceptor interceptor) { + public CommunicateToMainService(CustomConfigurationMapper customConfigurationMapper, Interceptor interceptor, + ShareFileMapper shareFileMapper, TaskService taskService) { + this.shareFileMapper = shareFileMapper; + this.taskService = taskService; messageId = new AtomicInteger(); promises = new HashMap<>(); ips = new HashMap<>(); @@ -136,7 +137,6 @@ public class CommunicateToMainService { protected void initChannel(NioSocketChannel channel) { channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(100000000, 4, 4)); channel.pipeline().addLast(new MessageCodec()); -// channel.pipeline().addLast(new LoggingHandler(LogLevel.WARN)); channel.pipeline().addLast(new MyChannelInboundHandlerAdapter()); } }).connect(ip, 7777).sync(); @@ -159,7 +159,6 @@ public class CommunicateToMainService { protected void initChannel(NioSocketChannel channel) { channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(100000000, 4, 4)); channel.pipeline().addLast(new MessageCodec()); -// channel.pipeline().addLast(new LoggingHandler(LogLevel.WARN)); channel.pipeline().addLast(new MyChannelInboundHandlerAdapter()); } }).connect(ip, 9999).sync(); @@ -174,7 +173,6 @@ public class CommunicateToMainService { scheduledExecutorService.scheduleAtFixedRate(() -> { if(channelFuture == null) return; - channelFuture.channel().writeAndFlush(IoUtil.generateStatusMessage(id, storagePath)); if(!taskService.getTasks().isEmpty()){ TaskStatusMessage message = new TaskStatusMessage(); message.setTasks(new HashSet<>(taskService.getTasks().values())); @@ -934,8 +932,7 @@ public class CommunicateToMainService { for (String path : task.getPaths()) { File file = new File(storagePath + task.getRelativePath() + path); if(file.isFile()){ - ArchiveEntry entry = new TarArchiveEntry(file, finalPath.relativize(file.toPath()).toString()); - + TarArchiveEntry entry = new TarArchiveEntry(file, finalPath.relativize(file.toPath()).toString()); aos.putArchiveEntry(entry); InputStream inputStream = Files.newInputStream(file.toPath()); byte[] buf = new byte[4096]; @@ -951,7 +948,7 @@ public class CommunicateToMainService { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - ArchiveEntry entry = new TarArchiveEntry(dir.toFile(), finalPath.relativize(dir).toString()); + TarArchiveEntry entry = new TarArchiveEntry(dir.toFile(), finalPath.relativize(dir).toString()); aos.putArchiveEntry(entry); aos.closeArchiveEntry(); return FileVisitResult.CONTINUE; @@ -959,7 +956,7 @@ public class CommunicateToMainService { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - ArchiveEntry entry = new TarArchiveEntry(file.toFile(), finalPath.relativize(file).toString()); + TarArchiveEntry entry = new TarArchiveEntry(file.toFile(), finalPath.relativize(file).toString()); aos.putArchiveEntry(entry); InputStream inputStream = Files.newInputStream(file.toFile().toPath()); byte[] buf = new byte[4096]; diff --git a/src/main/java/com/lion/snss/service/FileService.java b/src/main/java/com/lion/snss/service/FileService.java index 312c574..d7cbd8f 100644 --- a/src/main/java/com/lion/snss/service/FileService.java +++ b/src/main/java/com/lion/snss/service/FileService.java @@ -8,7 +8,6 @@ import com.lion.snss.pojo.ShareFile; import com.lion.snss.pojo.User; import com.lion.snss.util.IoUtil; import com.lion.snss.util.Response; -import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -29,20 +28,23 @@ import java.util.Objects; public class FileService { String storagePath; - @Resource +// @Resource ShareFileMapper shareFileMapper; - @Resource +// @Resource CommunicateToMainService communicateToMainService; - @Resource +// @Resource Interceptor interceptor; HashMap ipAndShareCode; - public FileService(CustomConfigurationMapper customConfigurationMapper){ + public FileService(CustomConfigurationMapper customConfigurationMapper, ShareFileMapper shareFileMapper, CommunicateToMainService communicateToMainService, Interceptor interceptor){ + this.communicateToMainService = communicateToMainService; + this.shareFileMapper = shareFileMapper; + this.interceptor = interceptor; storagePath = customConfigurationMapper.selectValue(CustomConfigurationMapper.PATH); ipAndShareCode = new HashMap<>(); } diff --git a/src/main/java/com/lion/snss/util/IoUtil.java b/src/main/java/com/lion/snss/util/IoUtil.java index fe16998..56323ab 100644 --- a/src/main/java/com/lion/snss/util/IoUtil.java +++ b/src/main/java/com/lion/snss/util/IoUtil.java @@ -3,132 +3,53 @@ package com.lion.snss.util; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; -import cn.hutool.system.oshi.CpuInfo; -import cn.hutool.system.oshi.OshiUtil; -import com.lion.snss.message.StatusMessage; import com.lion.snss.message.PairMessage; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.Data; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.catalina.connector.ClientAbortException; import org.springframework.http.HttpHeaders; -import oshi.hardware.CentralProcessor; -import oshi.hardware.GlobalMemory; -import oshi.hardware.HWDiskStore; -import oshi.hardware.NetworkIF; -import oshi.software.os.OperatingSystem; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; @Data @Slf4j public class IoUtil { - static long ioRead; - static long ioWrite; - static long networkSend; - static long networkReceive; - static NetworkIF networkIF; - static List diskStores; - static CpuInfo cpuInfo; - static GlobalMemory globalMemory; - - static long send; - static long sendNow; - static long receive; - static long receiveNow; - - static long read; - static long readNow; - static long write; - static long writeNow; - - static ScheduledExecutorService thread; + @Getter + static String ip; static { init(); } public static void init(){ - thread = Executors.newScheduledThreadPool(1); - List networkIFs = OshiUtil.getNetworkIFs(); - cpuInfo = OshiUtil.getCpuInfo(); - globalMemory = OshiUtil.getMemory(); - - for (NetworkIF nif : networkIFs) - if (nif.getName().startsWith("eth0") || nif.getName().startsWith("ens")) { - networkIF = nif; - break; - } - - if(networkIF == null) - log.error("网卡 eth0 不存在"); - else{ - send = networkIF.getBytesSent(); - receive = networkIF.getBytesRecv(); + try { + ip = getPublicIP(); + }catch (IOException | URISyntaxException e){ + log.info("当前机器网卡为内网ip且无法获取公网ip,程序退出"); + Runtime.getRuntime().exit(1); } - - diskStores = OshiUtil.getDiskStores(); - for (HWDiskStore diskStore : diskStores) { - read += diskStore.getReadBytes(); - write += diskStore.getWriteBytes(); - } - thread.scheduleAtFixedRate(IoUtil::monitor, 0, 1, TimeUnit.SECONDS); } - private static void monitor(){ - networkIF.updateAttributes(); - sendNow = networkIF.getBytesSent(); - receiveNow = networkIF.getBytesRecv(); - networkSend = sendNow - send; - networkReceive = receiveNow - receive; - send = sendNow; - receive = receiveNow; - - writeNow = 0; - readNow = 0; - for (HWDiskStore diskStore : diskStores) { - diskStore.updateAttributes(); - writeNow += diskStore.getWriteBytes(); - readNow += diskStore.getReadBytes(); - } - ioWrite = writeNow - write; - ioRead = readNow - read; - write = writeNow; - read = readNow; - } public static PairMessage generatePairMessage(){ PairMessage pairMessage = new PairMessage(); - String ip = networkIF.getIPv4addr()[0].split("/")[0]; - String privateIPPattern = "(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)"; - if(Pattern.compile(privateIPPattern).matcher(ip).find()) - try { - ip = getPublicIP(); - }catch (IOException | URISyntaxException e){ - log.info("当前机器网卡为内网ip且无法获取公网ip,程序退出"); - Runtime.getRuntime().exit(1); - } + String ip; + try { + ip = getPublicIP(); + }catch (IOException | URISyntaxException e){ + log.info("当前机器网卡为内网ip且无法获取公网ip,程序退出"); + Runtime.getRuntime().exit(1); + return null; + } pairMessage.setIp(ip); pairMessage.setHostname(NetUtil.getLocalHostName()); - - OperatingSystem os = OshiUtil.getOs(); - pairMessage.setSystem(os.getFamily() + " " + os.getVersionInfo().toString()); - pairMessage.setCpuArch(System.getProperty("os.arch")); - - CentralProcessor processor = OshiUtil.getHardware().getProcessor(); - pairMessage.setCpuName(processor.getProcessorIdentifier().getName().strip()); - pairMessage.setCpuCore(processor.getPhysicalProcessorCount()); - pairMessage.setCpuThread(processor.getLogicalProcessorCount()); return pairMessage; } @@ -151,41 +72,6 @@ public class IoUtil { return json.substring(startIndex + 1, endIndex); } - public static StatusMessage generateStatusMessage(int id, String path){ - StatusMessage statusMessage = new StatusMessage(); - statusMessage.setId(id); - - statusMessage.setTotalMemory(globalMemory.getTotal()); - statusMessage.setUsedMemory(globalMemory.getTotal() - globalMemory.getAvailable()); - statusMessage.setUsedMemoryPercentage(numberFormat((double) statusMessage.getUsedMemory() / statusMessage.getTotalMemory())); - - File file = new File(path); - statusMessage.setTotalSpace(file.getTotalSpace()); - statusMessage.setUsedSpace(file.getTotalSpace() - file.getFreeSpace()); - statusMessage.setUsedSpacePercentage(numberFormat((double) statusMessage.getUsedSpace() / statusMessage.getTotalSpace())); - - statusMessage.setSystemLoad(OshiUtil.getHardware().getProcessor().getSystemLoadAverage(3)); - statusMessage.setUsedCpuPercentage(numberFormat(100 - OshiUtil.getCpuInfo().getFree())); - - statusMessage.setIoRead(ioRead); - statusMessage.setIoWrite(ioWrite); - statusMessage.setNetworkReceive(networkReceive); - statusMessage.setNetworkSend(networkSend); - - statusMessage.setSystemUpTime(OshiUtil.getOs().getSystemUptime()); - statusMessage.setSystemBootTime(OshiUtil.getOs().getSystemBootTime()); - - return statusMessage; - } - - public static double numberFormat(double number){ - if(number <= 0) - return number; - if(number < 1) - return Double.parseDouble(String.format("%.1f", number * 100)); - else - return Double.parseDouble(String.format("%.1f", number)); - } public static void export(HttpServletRequest request, HttpServletResponse response, String path) { File file = new File(path);