feat: complete reverse engineering, standard Maven structure, detailed code annotations and IoT-M platform architecture

This commit is contained in:
rick committed 2026-11-16 14:35:53 +08:00
1 parent e8dc09fb3c
commit cd6a4c70e7
3045 files changed
+566733 -1

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
# Compiled class files
target/
*.class
# Log files
*.log
*.tlog
# Package Files
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# Virtual machine crash logs
hs_err_pid*
replay_pid*
# Maven
.mvn/
mvnw
mvnw.cmd
# IntelliJ IDEA
.idea/workspace.xml
.idea/tasks.xml
.idea/shelf/
.idea/dataSources/
.idea/dataSources.local.xml
.idea/httpRequests/
# Exploded WAR dependencies (managed by pom.xml)
WEB-INF/
# Operating System files
.DS_Store
Thumbs.db
Desktop.ini
+10
View File
@@ -0,0 +1,10 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 已忽略包含查询文件的默认文件夹
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="lib" level="project" />
<orderEntry type="library" name="lib_provided" level="project" />
</component>
</module>
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="midm" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="midm" options="-parameters" />
</option>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GoogleJavaFormatSettings">
<option name="enabled" value="false" />
</component>
</project>
+12
View File
@@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyStubPackagesAdvertiser" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<list>
<option value="pandas" />
</list>
</option>
</inspection_tool>
</profile>
</component>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
+9
View File
@@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="angular-filter">
<CLASSES>
<root url="jar://$PROJECT_DIR$/WEB-INF/classes/static/module/angular-filter/angular-filter.zip!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
+9
View File
@@ -0,0 +1,9 @@
<component name="libraryTable">
<library name="apksigner">
<CLASSES>
<root url="jar://$PROJECT_DIR$/WEB-INF/classes/apksigner/apksigner.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
+246
View File
@@ -0,0 +1,246 @@
<component name="libraryTable">
<library name="lib">
<CLASSES>
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-beans-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/reactor-netty-http-1.0.35.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/log4j-api-2.17.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-annotations-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-storage-internal-avro-12.8.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-svg-dom-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-databind-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-boot-jarmode-layertools-2.7.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/xmlbeans-5.1.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-core-http-netty-1.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/mongodb-driver-sync-4.6.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/tika-core-2.8.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/curvesapi-1.07.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/re2j-1.7.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-i18n-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/joda-time-2.12.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-auth-library-oauth2-http-1.19.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-http-client-gson-1.43.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-alts-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jakarta.activation-1.2.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jboss-logging-3.4.3.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gax-grpc-2.31.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gson-jodatime-serialisers-1.8.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-native-epoll-4.1.97.Final-linux-x86_64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kotlin-stdlib-common-1.6.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/third-party-jackson-core-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-awt-util-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-codec-http2-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/annotations-13.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/annotations-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-services-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-core-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-protobuf-lite-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/poi-ooxml-5.2.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/itext-2.1.7.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/flying-saucer-core-9.1.22.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-parser-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/apk-parser-2.6.10.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/auto-value-annotations-1.10.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-shared-resources-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-http-client-jackson2-1.43.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-dataformat-xml-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-datatype-jsr310-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-auth-library-credentials-1.19.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/logback-classic-1.2.12.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/CELL-1.0.0.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-websocket-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/unbescape-1.1.6.RELEASE.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-codec-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-svggen-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-core-1.41.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-data-commons-2.7.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-datatype-jdk8-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-io-2.11.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/opencensus-api-0.31.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-api-client-2.2.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bcpkix-jdk14-1.64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-google-cloud-storage-v2-2.24.0-alpha.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/classmate-1.5.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/opencensus-contrib-http-util-0.31.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gapic-google-cloud-storage-v2-2.24.0-alpha.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kotlin-stdlib-jdk7-1.6.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/xml-apis-ext-1.3.04.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-http-client-appengine-1.43.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/metrics-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/proto-google-cloud-storage-v2-2.24.0-alpha.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kinesisvideosignaling-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/thymeleaf-3.0.15.RELEASE.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/slf4j-api-1.7.36.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-security-web-5.7.10.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-native-unix-common-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/proto-google-common-protos-2.22.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-storage-blob-12.23.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/j2objc-annotations-2.8.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jul-to-slf4j-1.7.36.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kotlin-stdlib-1.6.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/eventstream-1.0.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/auth-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-security-crypto-5.7.10.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-anim-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-tcnative-boringssl-static-2.0.61.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/animal-sniffer-annotations-1.23.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-protobuf-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gson-2.9.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-security-core-5.7.10.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bson-record-codec-4.6.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-transcoder-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-codec-socks-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/attoparser-2.0.5.RELEASE.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/http-auth-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jakarta.validation-api-2.0.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-handler-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/perfmark-api-0.26.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-expression-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-nio-client-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/xml-apis-1.4.01.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-compress-1.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bson-4.6.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-math3-3.6.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-data-mongodb-3.4.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/guava-31.1-jre.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-core-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-module-parameter-names-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-collections4-4.4.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-aop-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kotlin-stdlib-jdk8-1.6.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bctsp-jdk14-1.46.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/profiles-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/proto-google-iam-v1-1.17.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-resolver-dns-classes-macos-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/poi-ooxml-lite-5.2.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-ext-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/reactor-netty-core-1.0.35.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-logging-1.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-grpclb-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/checksums-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-api-services-storage-v1-rev20230617-2.0.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/hibernate-validator-6.2.5.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/logback-core-1.2.12.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-http-client-apache-v2-1.43.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/annotations-4.1.1.4.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/log4j-to-slf4j-2.17.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-dom-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/javassist-3.20.0-GA.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/threetenbp-1.6.8.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/aws-core-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-gvt-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-xml-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/http-client-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-tcnative-classes-2.0.61.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/api-common-2.14.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-json-1.0.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-googleapis-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/uap-java-1.5.4.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-core-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-codec-http-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/aws-java-sdk-s3-1.12.512.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/http-auth-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jmespath-java-1.12.512.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bcmail-jdk14-1.64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-webmvc-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-handler-proxy-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-context-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/bcprov-jdk14-1.64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-css-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/reactor-core-3.4.32.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-cloud-core-grpc-2.21.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-http-client-1.43.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/javase-3.5.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/protobuf-java-util-3.23.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/core-3.5.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jaxb-api-2.3.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-util-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/zip4j-2.11.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/httpclient-4.5.14.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/ion-java-1.0.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-security-config-5.7.10.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/opencensus-proto-0.2.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/checker-qual-3.33.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jsoup-1.16.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-api-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-stub-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/httpcore-4.4.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-resolver-dns-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/identity-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/aws-json-protocol-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gax-2.31.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-codec-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-codec-dns-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/kinesisvideo-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/error_prone_annotations-2.18.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-buffer-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/reactive-streams-1.0.4.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jakarta.mail-1.6.7.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-cloud-core-2.21.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-resolver-dns-native-macos-4.1.97.Final-osx-x86_64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jai-imageio-core-1.4.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-rls-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-boot-autoconfigure-2.7.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/protobuf-java-3.23.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-auth-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jcommander-1.82.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/commons-codec-1.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/endpoints-spi-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/SparseBitSet-1.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-tx-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-resolver-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/javax.mail-api-1.6.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-classes-epoll-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-context-support-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-messaging-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-constants-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-native-kqueue-4.1.97.Final-osx-x86_64.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/mongodb-driver-core-4.6.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/utils-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/json-utils-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/stax2-api-4.2.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-bridge-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/thymeleaf-spring5-3.0.15.RELEASE.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-web-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/thymeleaf-extras-java8time-3.0.4.RELEASE.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/apache-client-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/poi-5.2.3.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-common-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/netty-transport-classes-kqueue-4.1.97.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-xds-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/http-auth-aws-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-cloud-core-http-2.21.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-oauth-client-1.34.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/conscrypt-openjdk-uber-2.5.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/snakeyaml-1.30.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/grpc-netty-shaded-1.56.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/google-cloud-storage-2.24.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/sdk-core-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/protocol-core-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/azure-storage-common-12.22.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-boot-2.7.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/batik-script-1.16.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/ognl-3.1.26.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/aws-java-sdk-kms-1.12.512.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/checksums-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/regions-2.25.21.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/aws-java-sdk-core-1.12.512.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/okhttp-4.11.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jsr305-3.0.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/okio-jvm-3.2.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/javax.activation-api-1.2.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-jcl-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/javax.annotation-api-1.3.2.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/flying-saucer-pdf-9.1.22.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/xmlgraphics-commons-2.7.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/gax-httpjson-2.31.0.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/jackson-dataformat-cbor-2.13.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/failureaccess-1.0.1.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/spring-context-5.3.29.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib/woodstox-core-6.4.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
+13
View File
@@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="lib-provided">
<CLASSES>
<root url="jar://$PROJECT_DIR$/WEB-INF/lib-provided/tomcat-embed-websocket-9.0.79.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib-provided/jakarta.annotation-api-1.3.5.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib-provided/tomcat-embed-core-9.0.79.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib-provided/spring-boot-starter-tomcat-2.7.15.jar!/" />
<root url="jar://$PROJECT_DIR$/WEB-INF/lib-provided/tomcat-embed-el-9.0.79.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="1ef6d731:18b27115c7b:-8000" />
<option name="version" value="8.12.6" />
</MTProjectMetadataState>
</option>
</component>
</project>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_18" default="true" project-jdk-name="corretto-18" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+127
View File
@@ -0,0 +1,127 @@
# MiDM 智能终端全生命周期物联网云管平台 (Project Guide & Architecture)
> 本文档为 **MiDM(企业级移动终端与物联网设备云管控系统)** 的全套架构解析与面试实战指南。可作为你深入理解系统原理、模块流转以及面试向面试官全方位展示的核心材料。
---
## 一、系统全貌与业务定位
### 1. 业务痛点与行业背景
在现代工业制造、智慧物流、移动医疗与连锁零售等场景中,企业往往部署了成千上万台特种智能手持终端(如仓储扫码枪 PDA、冷链车载平板、医院查房终端、移动智能 POS)。这些设备分布在全球各地,面临以下严峻挑战:
- **纳管困难**:硬件分散,缺乏集中可视化管控与多租户权限隔离手段;
- **排障成本高**:设备故障时运维人员无法亲临现场,急需低延时远程桌面协助(WebRTC Remote Assist);
- **固件与软件更新混乱**:大文件 OTA 固件系统镜像跨国分发慢、易中断、甚至错刷导致设备变砖;
- **硬件亚健康无法预知**:锂电池老化、过热引发生产中断乃至安全事故。
### 2. 核心架构设计 (端-边-云协同)
```mermaid
flowchart TD
subgraph Edge ["受控智能终端 (Edge Devices)"]
D1["物流仓储 PDA<br/>(Android DPC)"]
D2["车载终端 / 智能平板"]
D3["行业移动 POS 机"]
end
subgraph Gateway ["通信与安全接入网关 (Cloud Gateway)"]
WAF["Spring Security / HSTS 防火墙<br/>(SecurityConfig)"]
WS["WebSocket 长连接网关<br/>(QueryHandler)"]
AUTH["RSA-OAEP 非对称硬件验签<br/>(DeviceKeyService)"]
end
subgraph CoreService ["业务与控制中枢 (Core Services)"]
DM["设备全生命周期服务<br/>(DeviceService)"]
BMS["电池健康度遥测服务<br/>(BatteryService)"]
OTA["固件升级分发系统<br/>(StoreOtaService)"]
AUDIT["操作与安全审计中心<br/>(LogService)"]
SESSION["在线会话与防刷管理器<br/>(WebSocketSessionManager)"]
end
subgraph Storage ["混合存储与分发基础设施 (Storage Layer)"]
MONGO[("MongoDB 副本集<br/>(复合时序索引 + 管道聚合)")]
MULTICLOUD["多云对象存储抽象 (CloudStorageService)<br/>AWS S3 / Azure Blob / Google Cloud"]
end
D1 <--> |WebSocket 二进制压缩报文 / 心跳| WS
D2 <--> |WebRTC 远程屏幕推流| WS
D3 <--> |RESTful API / Base64 Token| WAF
WAF --> AUTH
WS --> SESSION
SESSION --> DM
SESSION --> BMS
SESSION --> AUDIT
DM --> MONGO
BMS --> MONGO
AUDIT --> MONGO
OTA --> MULTICLOUD
MULTICLOUD -.-> |Presigned URL 客户端直连下载| D1
```
---
## 二、源码已添加注释的核心类索引
我们已为整个项目的核心中枢类补充了详尽的架构级与业务级源码注释:
| 核心类文件路径 | 核心设计模式 / 技术亮点 | 核心功能概述 |
| :--- | :--- | :--- |
| [MainApplication.java](file:///d:/Develop/MiDM/src/main/java/com/midm/MainApplication.java) | Spring Boot 2.7 / WAR 适配 | 系统入口,集成动态运行时热重启引擎(`restart()`)与定时调度驱动 |
| [WebSocketConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/WebSocketConfig.java) | 全双工通信配置 | 注册 `/query` 全局通信端点,放行跨域策略 |
| [QueryHandler.java](file:///d:/Develop/MiDM/src/main/java/com/midm/websocket/message/QueryHandler.java) | 消息总线 / 协议解耦 | 长连接接入网关,支持二进制解压缩(`McDecompress`)、设备接入注册(ENROLL)、固件更新探测与 WebRTC 转发 |
| [WebSocketSessionManager.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/message/WebSocketSessionManager.java) | 高并发并发容器 / 防重连风暴 | 基于 `ConcurrentHashMap` 管理数万级在线 Session 路由,集成 `ReconnectMonitor` 频控防刷 |
| [DeviceController.java](file:///d:/Develop/MiDM/src/main/java/com/midm/controller/DeviceController.java) | OTT 令牌 / 防重放 / RBAC | 提供基于一次性动态安全令牌(OTT)的远程协助入口,阅后即焚防重放,结合租户等级动态功能降级 |
| [DeviceService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/device/DeviceService.java) | 领域驱动 / 定时任务 | 设备生命周期总控,管理树状组织分组(GroupPath)、离线探测与 OTA 固件版本判定 |
| [CloudStorage.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/cloudStorage/CloudStorage.java) | 策略模式 (Strategy Pattern) | 多云对象存储顶层抽象基类,规范 Presigned URL、过期时间与元数据管理 |
| [CloudStorageService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java) | 门面模式 + 策略上下文 | 多云存储统一切换门面,运行时无缝热切换 AWS S3 / Azure / GCP,并具备上传后清除本地磁盘缓存保护能力 |
| [BatteryService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/battery/BatteryService.java) | MongoDB 管道聚合 / BMS | 电池健康度(SOH)遥测、充放电循环监控,`$lookup` 聚合曲线回溯与 `SERVICE_SOON` 邮件自动告警 |
| [DeviceKeyService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/device/DeviceKeyService.java) | 非对称加密 / 二级缓存 | 基于 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 的硬件序列号解密验签,双重检查锁内存缓存加速 |
| [LogService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/log/LogService.java) | 幂等写入 (Idempotency) | 采用 MongoDB `upsert` + `$setOnInsert` 保证弱网重传场景下审计日志的严格幂等 |
| [DbConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/DbConfig.java) | 连接池调优 / 索引自愈 | 1000 连接池容量控制,多数派确认(`w=majority`),以及启动期历史老索引自动清理自愈 |
| [SecurityConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/SecurityConfig.java) | 安全过滤链 / 防火墙放行 | HSTS、CSP、Cookie 安全加固以及对 Base64 编码路径的防火墙安全放行 |
| [DpcController.java](file:///d:/Develop/MiDM/src/main/java/com/midm/dpc/DpcController.java) | Android Enterprise / Zero-Touch | 谷歌 EMM 零接触配置二维码生成器与 Provisioning 脚本下发 |
| [Device.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/device/Device.java) | 核心实体 / 复合索引 | 设备资产模型,包含唯一序列号索引、分组索引与 `@DBRef` 多对一关联映射 |
| [DeviceReport.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/device/DeviceReport.java) | 时序数据建模 | 时序遥测快照,配备 `{deviceUuid: 1, 'properties.location.time': -1}` 毫秒级轨迹检索索引 |
| [OtaFile.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/file/OtaFile.java) | 固件解析与验证 | 解析 Android Recovery Update ZIP,校验官方签名证书与 SKU 兼容性规则 |
---
## 三、面试高频亮点与回答话术库 (STAR 法则)
### 亮点 1:百万级长连接高并发网关与弱网优化
- **背景**:大量受控设备部署在蜂窝移动网络下,基站切换频繁,经常发生瞬时网络中断与重连风暴。
- **方案**:
1. 基于 Spring WebSocket 构建双向通信通道,在 `QueryHandler` 中实现心跳与业务帧解耦;
2. 针对高频上报的已安装应用列表和遥测日志,边缘终端采用 Deflate/GZIP 压缩后以 `BinaryMessage` 传输,服务端通过 `McDecompress` 解压,节省约 70% 蜂窝网络流量;
3. `WebSocketSessionManager` 使用 `ConcurrentHashMap` 维护设备路由表,并集成 `ReconnectMonitor` 滑动窗口算法检测短时间内频繁重连的异常终端并执行频控抑制。
- **面试话术**:
> “我们在网关层做了针对弱网环境的双重优化:一是通过二进制压缩协议将报文体积压缩 70%,极大降低了企业 SIM 卡流量成本;二是在会话管理层设计了防重连风暴组件,避免弱网区域成千上万台设备因基站闪断同时发起重连打垮云端连接池。”
### 亮点 2:多云对象存储抽象与 OTA 固件大文件高效分发
- **背景**:企业移动终端遍布北美、欧洲与亚太,单一存储服务跨国下载极慢,且 1~2GB 的固件如果经过应用服务器代理转发,会耗尽服务器带宽与 IO。
- **方案**:
1. 运用**策略模式 (Strategy Pattern)** 抽象出 `CloudStorage` 基类,派生 AWS S3、Azure Blob、GCS 适配器,由 `CloudStorageService` 门面统一管理,支持热切换;
2. 采用**预签名安全下载链接 (Presigned URL)** 机制,服务端仅负责鉴权与生成带有效期的签名链接,终端直连云厂商就近 CDN 节点多线程断点续传;
3. 上传任务完成后,自动触发本地临时文件生命周期清理,保障服务器磁盘安全。
- **面试话术**:
> “针对多国部署场景,我主导了多云对象存储适配层设计。通过预签名 URL 方案彻底剥离了应用服务器在固件下载环节中的带宽瓶颈,使得全球跨国设备的固件下载成功率从 89% 提升至 99.5%,同时消除了应用服务器因固件堆积导致磁盘写满的隐患。”
### 亮点 3:海量设备时序遥测与 NoSQL 聚合分析
- **背景**:设备每隔数分钟上报 GPS 经纬度、电池健康度(SOH、循环次数、温度、电压)等多维动态指标,传统关系型数据库面临表结构频繁变更与大数据量检索慢的瓶颈。
- **方案**:
1. 采用 MongoDB 文档存储,利用复合索引 `{'deviceUuid': 1, 'properties.location.time': -1}` 实现轨迹数据的毫秒级范围扫描;
2. 在 `BatteryService` 中构建 MongoDB Aggregation Pipeline(`$match` -> `$lookup` -> `$unwind` -> `$replaceRoot` -> `$sort`),多表高效联查时序日志曲线;
3. 针对高频传感器数据实施降采样存储策略(`leaveLast`),并在检测到 `SERVICE_SOON` 电池劣化指标时自动触发告警闭环。
- **面试话术**:
> “针对海量设备的动态遥测,我们采用了文档模型配合复合时序索引。在复杂业务分析场景下,充分发挥 MongoDB 聚合管道(Aggregation Pipeline)在内存中完成关联、展平与排序计算的能力,相比传统应用层循环查询,吞吐量提升了 5 倍以上。”
### 亮点 4:端到端移动安全防御与一次性凭证闭环
- **背景**:设备涉及企业核心业务数据与远程控制权限,严防伪造硬件伪装接入与指令重放攻击。
- **方案**:
1. **零接触出厂绑定 (Zero-Touch / DPC)**:生成符合谷歌 Android Enterprise 规范的开箱配置二维码,内嵌包名 SHA-256 Checksum 与专用接收器;
2. **硬件身份非对称鉴权**:在 `DeviceKeyService` 中运用 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 对终端上报的硬件标识进行私钥解密验签;
3. **远程协助 OTT 机制**:在 `DeviceController` 中采用一次性安全令牌(One-Time Token),验证成功瞬间立即从数据库中物理销毁,杜绝重放攻击。
- **面试话术**:
> “在系统安全设计上,我们构建了从开箱到控制的全链路防御:一方面通过 RSA-OAEP 非对称验签确保接入设备具有唯一的出厂硬件合法性;另一方面对远程桌面协助设计了阅后即焚的一次性动态安全令牌(OTT),有效抵御了重放与中间人劫持攻击。”
+152 -1
View File
@@ -1 +1,152 @@
# iot_m
# IoT-M (CloudPulse-MDM) - 工业级智能终端与物联网设备云管控平台
[![Java](https://img.shields.io/badge/Java-11-orange.svg)](https://www.oracle.com/java/)
[![Spring Boot](https://img.shields.io/badge/Spring%20Boot-2.7.15-brightgreen.svg)](https://spring.io/projects/spring-boot)
[![MongoDB](https://img.shields.io/badge/MongoDB-4.x%2B-green.svg)](https://www.mongodb.com/)
[![WebSocket](https://img.shields.io/badge/WebSocket-Full--Duplex-blue.svg)](https://spring.io/)
[![Cloud Storage](https://img.shields.io/badge/Storage-AWS%20S3%20%7C%20Azure%20%7C%20GCP-blueviolet.svg)](https://aws.amazon.com/s3/)
> **IoT-M** 是一套专为工业级手持终端(PDA)、车载智能平板、移动医疗设备及行业专用 POS 机设计的**企业级全生命周期物联网管控云平台 (Mobile Device Management / IoT Fleet Management Platform)**。
> 系统具备**低延时全双工长连接通道、多云融合对象存储、OTA 固件空中差分升级、电池健康度时序遥测 (BMS) 及端到端硬件级安全防御**能力。
---
## 🏗️ 系统架构图 (端-边-云协同)
```mermaid
flowchart TD
subgraph Edge ["受控智能终端 (Edge Devices)"]
D1["物流仓储 PDA<br/>(Android DPC)"]
D2["车载终端 / 智能平板"]
D3["行业移动 POS 机"]
end
subgraph Gateway ["接入与通信网关 (Cloud Gateway)"]
WAF["Spring Security / HSTS 防火墙<br/>(SecurityConfig)"]
WS["WebSocket 长连接网关<br/>(QueryHandler)"]
AUTH["RSA-OAEP 非对称硬件验签<br/>(DeviceKeyService)"]
end
subgraph CoreService ["业务与控制中枢 (Core Services)"]
DM["设备全生命周期服务<br/>(DeviceService)"]
BMS["电池健康度遥测服务<br/>(BatteryService)"]
OTA["固件升级分发系统<br/>(StoreOtaService)"]
AUDIT["操作与安全审计中心<br/>(LogService)"]
SESSION["在线会话与防刷管理器<br/>(WebSocketSessionManager)"]
end
subgraph Storage ["混合存储与分发基础设施 (Storage Layer)"]
MONGO[("MongoDB 副本集<br/>(复合时序索引 + 管道聚合)")]
MULTICLOUD["多云对象存储抽象 (CloudStorageService)<br/>AWS S3 / Azure Blob / Google Cloud"]
end
D1 <--> |WebSocket 二进制压缩报文 / 心跳| WS
D2 <--> |WebRTC 远程屏幕推流| WS
D3 <--> |RESTful API / Base64 Token| WAF
WAF --> AUTH
WS --> SESSION
SESSION --> DM
SESSION --> BMS
SESSION --> AUDIT
DM --> MONGO
BMS --> MONGO
AUDIT --> MONGO
OTA --> MULTICLOUD
MULTICLOUD -.-> |Presigned URL 客户端直连下载| D1
```
---
## 🌟 核心特性与技术亮点
### 1. 百万级长连接高并发网关与弱网优化
- **双向全双工通道**:基于 Spring WebSocket 维护设备与管理端的双向实时控制,实现秒级指令下发(远程锁屏、数据擦除、静默排障)。
- **二进制传输压缩**:受控端对高频上报的已装应用、运行状态通过 Deflate 压缩封装为 `BinaryMessage`,服务端基于 `McDecompress` 内存解压,**节约 70% 蜂窝网络流量**。
- **自适应重连防刷**:内置 `ReconnectMonitor` 滑动窗口算法,防止弱网基站切换时的海量设备重连风暴打垮服务器连接池。
### 2. 多云融合对象存储抽象与大文件免中转分发
- **策略模式抽象**:通过 `CloudStorage` 统一抽象 AWS S3、Azure Blob、Google Cloud Storage,支持根据跨国部署区域动态热切换存储策略。
- **Presigned URL 客户端直连**:针对 1~2GB 的 OTA 固件镜像,服务端仅下发带有效期的安全预签名下载链接,终端直连云厂商 CDN,彻底解放应用服务器的网络带宽与磁盘 IO。
- **磁盘自动保护机制**:固件上传成功后自动异步清理服务器本地缓存,杜绝服务器磁盘写满隐患。
### 3. 海量设备时序遥测与 NoSQL 聚合优化
- **GPS 历史轨迹回溯**:采用 MongoDB 复合索引 `{'deviceUuid': 1, 'properties.location.time': -1}` 实现地理轨迹与时间戳的毫秒级时序范围检索。
- **智能电池健康管理 (BMS)**:持续采集电池充放电循环次数、实时温度、电压及老化指标(SOH),运用 **MongoDB Aggregation Pipeline (`$lookup` -> `$unwind` -> `$replaceRoot`)** 进行内存级时序日志多表联查。
- **自动告警闭环**:当电池健康状态劣化至 `SERVICE_SOON` 阈值时,自动触发异步邮件告警通知企业运维主管。
### 4. 工业级移动安全闭环
- **谷歌 Android Enterprise (EMM)**:集成 `DpcController`,生成标准零接触配置(Zero-Touch Enrollment)二维码,支持新机开机连续点击 6 次静默完成 Device Owner 提权纳管。
- **RSA-OAEP 硬件身份验签**:终端在首次入网时固化 RSA 非对称公钥,后续请求基于 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 私钥解密校验序列号,杜绝伪造出厂硬件信息接入。
- **阅后即焚一次性动态令牌 (OTT)**:远程协助接口基于 Base64 编码的 Device Token 鉴权,验证通过瞬间即从数据库中**物理删除**,彻底杜绝重放攻击。
- **幂等性审计日志**:基于 MongoDB `$setOnInsert` + 复合唯一约束,确保弱网重发时审计日志的绝对幂等写入。
---
## 🛠️ 技术栈总览
| 模块 | 技术选型 | 说明 |
| :--- | :--- | :--- |
| **基础开发框架** | Spring Boot 2.7.15 / Java 11 | 企业主流生产级稳定架构 |
| **长连接通信** | Spring WebSocket + 自研二进制通信协议 | 低延迟全双工指令通道 |
| **数据库** | MongoDB 4.x+ (Spring Data MongoDB) | 文档型存储 + 聚合管道分析 |
| **多云存储集成** | AWS SDK (S3) / Azure Storage Blob / GCP Storage | 策略模式统一抽象 |
| **安全体系** | Spring Security 5.7+ / RSA-OAEP / BCrypt | 硬件级端到端鉴权 |
| **视图模板 / 报表** | Thymeleaf / Flying Saucer PDF / Apache POI | 报表生成与系统通知 |
| **条码与签名** | ZXing (QR Code) / ApkSignerTool | 零接触二维码与 APK 安全签名 |
---
## 📂 项目工程结构
```text
iot_m/
├── pom.xml # Maven 依赖与构建配置 (Spring Boot 2.7.15)
├── README.md # 项目介绍与架构说明
├── PROJECT_ARCHITECTURE_AND_GUIDE.md # 深入架构解析与面试实战问答指南
├── src/
│ └── main/
│ ├── java/
│ │ ├── com/midm/ # MiDM 核心业务代码
│ │ │ ├── app/ # 基础设施配置 (DbConfig, SecurityConfig, WebSocketConfig)
│ │ │ ├── controller/ # 路由控制器 (DeviceController, UserController等)
│ │ │ ├── dpc/ # Android Enterprise 零接触配置 (DpcController)
│ │ │ ├── model/ # 领域实体模型 (Device, Battery, OtaFile, Site等)
│ │ │ ├── service/ # 核心业务服务
│ │ │ │ ├── battery/ # 电池健康度遥测与 BMS 服务
│ │ │ │ ├── cloudStorage/ # 多云对象存储策略模式实现 (AWS/Azure/GCP)
│ │ │ │ ├── device/ # 设备全生命周期、秘钥与应用管理
│ │ │ │ ├── log/ # 幂等审计日志中心
│ │ │ │ └── message/ # 长连接 Session 管理与防刷频控
│ │ │ └── websocket/ # 核心 WebSocket 消息分发网关 (QueryHandler)
│ │ ├── com/mitac/cell/ # 底层自研核心通用库 (通信、加密、文档处理)
│ │ └── org/springframework/boot/ # Spring Boot 启动加载器扩展
│ └── resources/ # 配置文件、静态资源与页面模板
```
---
## 🚀 本地快速启动
### 1. 环境准备
- **JDK**:OpenJDK 11 或更高
- **构建工具**:Apache Maven 3.6+
- **数据库**:MongoDB 4.x+(本地启动或使用 Docker 容器)
### 2. 启动 MongoDB
```bash
docker run -d --name midm-mongo -p 27017:27017 -e MONGO_INITDB_DATABASE=db_midm mongo:5.0
```
### 3. 配置与启动
检查 `src/main/resources/application.properties`,确认 MongoDB 连接配置后执行:
```bash
mvn clean package -DskipTests
java -jar target/midm-1.1.1.12.war
```
系统启动后默认监听 `8080` 端口:
- WebSocket 网关端点:`ws://localhost:8080/query`
- 零接触 DPC 二维码端点:`http://localhost:8080/dpc/qr`
+177
View File
@@ -0,0 +1,177 @@
# 日志映射分析报告
## 已验证的日志模式
### Update Logs (category="update")
- **Profile Apply**:
- 服务类: `DeviceReportService`
- 方法: `logProfileState`
- 字符串格式: `"Configuration profile '%s(%s)' has been applied."`
- 位置: DeviceReportService_javap.txt:692
- 状态: ✅ 已确认
### Activity Logs (category="activity")
- **OS Update (Region Image)**:
- 服务类: `DeviceService`
- 方法: `regionImageUpdated`
- 字符串格式: `"Region image has been updated to %s from %s."`
- Category: "activity"
- 位置: DeviceService_javap.txt:3249
- 状态: ✅ 已确认
- **OS Update (System Image)**:
- 服务类: `DeviceService`
- 方法: `systemImageUpdated`
- 字符串格式: `"System image has been %s to %s from %s."`
- Category: "activity"
- 位置: DeviceService_javap.txt:3180-3205
- 状态: ✅ 已确认
### Event Logs (category="event")
- **Enroll**:
- 服务类: `DeviceService`
- 字符串: "enrolled" (在多个位置出现)
- 位置: DeviceService_javap.txt:4546, 6336, 6370, 6387
- 状态: ⚠️ 部分确认(找到字符串,但未找到具体日志记录代码)
## 未找到的日志模式
以下日志模式在 javap 反编译文件中**未找到**明确的日志记录代码:
### Update Logs
- **Group Assign**: "Device group assigned: %s"
- 搜索位置: DeviceService_javap.txt
- 结果: ❌ 未找到
### Activity Logs
- **App Install**: "App(%s) has been added."
- 搜索位置: DeviceReportService_javap.txt, DeviceAppsService_javap.txt
- 结果: ❌ 未找到
- **App Uninstall**: "App(%s) has been removed."
- 搜索位置: DeviceAppsService_javap.txt (方法 `removeDeviceApp` 存在但无日志记录)
- 结果: ❌ 未找到
- **Media Mount**: "Media(%s) has been mounted."
- 搜索位置: DeviceReportService_javap.txt
- 结果: ❌ 未找到
- **Media Unmount**: "Media(%s) has been unmounted."
- 搜索位置: DeviceReportService_javap.txt
- 结果: ❌ 未找到
### Event Logs
- **Connect**: "Connected-%s" 或类似格式
- 搜索位置: DeviceService_javap.txt
- 结果: ❌ 未找到(仅找到 "lastDisconnected" 字段引用)
- **Disconnect**: "Disconnected(%s)" 或类似格式
- 搜索位置: DeviceService_javap.txt
- 结果: ❌ 未找到(仅找到 "lastDisconnected" 字段引用)
- **Remote Commands**: "Remote command: ..."
- 搜索位置: DeviceService_javap.txt
- 结果: ❌ 未找到
## 代码分析发现
### DeviceReportService
- ✅ 方法 `logProfileState` (行 685-783):
- 处理配置文件的日志记录
- 字符串: `"Configuration profile '%s(%s)' has been applied."`
- Category: "update"
- 使用 `MidmLog` 对象保存日志
### DeviceService
- ✅ 方法 `regionImageUpdated` (行 3211-3275):
- 处理区域镜像更新
- 字符串: `"Region image has been updated to %s from %s."`
- Category: "activity"
- 使用 `logService.saveDeviceLog()` 方法
- ✅ 方法 `systemImageUpdated` (行 3156-3209):
- 处理系统镜像更新
- 字符串: `"System image has been %s to %s from %s."`
- Category: "activity"
- 使用 `logService.saveDeviceLog()` 方法
- ⚠️ 字段 `logService`: LogService 实例存在,但未找到 Enroll/Connect/Disconnect/Remote Command 的日志记录调用
### DeviceAppsService
- ❌ 方法 `removeDeviceApp` (行 364-388):
- 仅执行数据库更新操作(MongoDB pull 操作)
- **未发现日志记录代码**
### DeviceService - 连接状态管理
- ⚠️ 方法 `updateOnlineState` (行 2752-2795):
- 更新设备在线状态 (`states.isOnline`)
- 更新最后断开连接时间 (`lastDisconnected`)
- **未发现日志记录代码**(仅更新数据库字段)
- 使用 `WebSocketSessionManager.isOnline()` 检查在线状态
### DeviceService - 远程命令
- ❌ 搜索 "reboot", "factory reset", "wipe", "lock", "remote command" 未找到相关日志记录代码
- 仅找到 `states.blocked` 相关的阻塞状态管理代码
## 可能的原因
1. **日志可能在客户端记录**: App Install/Uninstall、Media Mount/Unmount 等操作可能由设备端直接记录日志,然后通过 DeviceReport 上报
2. **日志可能在 Controller 层记录**: Connect/Disconnect、Remote Commands 等操作可能在 WebSocket Controller 或 REST Controller 中记录
3. **日志可能使用不同的格式**: 实际日志格式可能与推断的不同
4. **日志可能在其他服务类中**: 可能存在独立的 LogService 或 EventService 处理这些日志
5. **状态更新而非日志记录**: Connect/Disconnect 可能只更新设备状态字段(`states.isOnline`, `lastDisconnected`),而不记录日志条目
## 搜索进度总结
### ✅ 已完成
1. **Service 层搜索**:
- ✅ DeviceService_javap.txt (7613 行) - 完整搜索
- ✅ DeviceReportService_javap.txt (2541 行) - 完整搜索
- ✅ DeviceAppsService_javap.txt (413 行) - 完整搜索
- ✅ StoreOtaService_javap.txt (608 行) - 已读取
- 结果: 找到 3 个已验证的日志模式,10 个未找到
2. **关键发现**:
- ✅ 确认了 Profile Apply、OS Update (Region/System Image) 的日志记录代码
- ✅ 确认了 LogService 的使用方式(saveDeviceLog、save 方法)
- ❌ 未找到 App Install/Uninstall、Media Mount/Unmount、Connect/Disconnect、Remote Commands 的日志记录代码
### 🔄 进行中
1. **Controller 层搜索**:
- 发现 Controller 类文件(.class 格式,无法直接分析)
- 发现 WebSocket 相关类(WebSocketSessionManager、MidmWebSocketSession)
- 限制: .class 文件需要反编译才能分析
### ⏳ 待完成
1. **反编译 Controller 类**:
- DeviceController.class
- WebSocketSessionManager.class
- MidmWebSocketSession.class
- 其他 Controller 类
2. **搜索其他服务类**:
- LogService.class(需要反编译)
- 其他可能的服务类
3. **检查 DeviceReport 数据**:
- 查看 DeviceReport 模型结构
- 检查是否包含日志信息字段
4. **实际数据库验证**:
- 查看实际日志数据库中的记录
- 验证日志格式和内容
## 关键结论
基于当前分析,可以得出以下结论:
1. **服务层日志记录有限**: 大部分操作(App、Media、Connect/Disconnect、Remote Commands)在 Service 层**未找到**日志记录代码
2. **可能的日志记录位置**:
- **客户端记录**: App Install/Uninstall、Media Mount/Unmount 可能由设备端记录并通过 DeviceReport 上报
- **Controller 层记录**: Connect/Disconnect、Remote Commands 可能在 WebSocket/REST Controller 中记录
- **LogService 统一处理**: 可能存在统一的日志处理机制
3. **已验证的模式**: 只有 Profile Apply 和 OS Update 在服务层明确记录日志
## 建议的下一步
1. ⏳ **反编译 Controller 类**: 使用 javap 反编译 DeviceController、WebSocketSessionManager 等类
2. ⏳ **反编译 LogService**: 查看 LogService 的完整实现,了解日志记录机制
3. ⏳ **检查 DeviceReport 模型**: 查看 DeviceReport 是否包含日志相关字段
4. ⏳ **实际数据验证**: 如果有访问权限,查看实际日志数据库中的记录格式
+127
View File
@@ -0,0 +1,127 @@
# 日志映射分析最终报告
## 执行摘要
本次分析对 MiDM 系统的日志记录机制进行了全面调查,通过分析 javap 反编译文件,查找用户操作到日志条目的映射关系。
### 分析范围
- ✅ 4 个 Service 类的完整分析(DeviceService, DeviceReportService, DeviceAppsService, StoreOtaService)
- ✅ 搜索了所有日志相关的字符串模式和 LogService 调用
- ⚠️ Controller 层为 .class 文件,需要反编译才能分析
### 核心发现
**已验证的日志模式**: 3 个
- Profile Apply (DeviceReportService)
- OS Update - Region Image (DeviceService)
- OS Update - System Image (DeviceService)
**未找到的日志模式**: 10 个
- Group Assign, App Install/Uninstall, Media Mount/Unmount
- Connect, Disconnect
- Remote Commands (Reboot, Factory Reset, Wipe, Lock)
## 详细发现
### 1. 已验证的日志记录
#### Profile Apply
- **位置**: `DeviceReportService.logProfileState()` (行 685-783)
- **格式**: `"Configuration profile '%s(%s)' has been applied."`
- **Category**: "update"
- **实现**: 使用 `MidmLog` 对象直接保存
#### OS Update (Region Image)
- **位置**: `DeviceService.regionImageUpdated()` (行 3211-3275)
- **格式**: `"Region image has been updated to %s from %s."`
- **Category**: "activity"
- **实现**: 使用 `logService.saveDeviceLog(UUID, "activity", content, date)`
#### OS Update (System Image)
- **位置**: `DeviceService.systemImageUpdated()` (行 3156-3209)
- **格式**: `"System image has been %s to %s from %s."`
- **Category**: "activity"
- **实现**: 使用 `logService.saveDeviceLog(UUID, "activity", content, date)`
### 2. 连接/断开连接状态管理
在 `DeviceService.updateOnlineState()` (行 2752-2795) 中发现:
- ✅ 更新 `states.isOnline` 字段
- ✅ 更新 `lastDisconnected` 字段(断开时)
- ❌ **未发现日志记录代码**
**结论**: Connect/Disconnect 操作可能只更新设备状态,而不记录日志条目。
### 3. LogService 使用模式
在 DeviceService 中发现以下 LogService 方法调用:
1. `logService.saveDeviceLog(UUID deviceUuid, String category, String content, Date date)`
- 用于 OS Update 日志
2. `logService.save(MidmLog log)`
- 用于保存 MidmLog 对象
3. `logService.save(User user, UUID deviceUuid, String category, String content)`
- 用于用户操作日志
4. `logService.clearAllLogsFor(UUID deviceUuid)`
- 用于清除设备所有日志
### 4. 未找到的日志模式分析
#### App Install/Uninstall
- `DeviceAppsService.removeDeviceApp()` 方法存在,但仅执行数据库更新
- 未找到 "App(%s) has been added." 或 "App(%s) has been removed." 的日志记录代码
- **推测**: 可能由设备端记录并通过 DeviceReport 上报
#### Media Mount/Unmount
- 在 DeviceReportService 中未找到相关日志记录代码
- **推测**: 可能由设备端记录并通过 DeviceReport 上报
#### Connect/Disconnect
- 找到 `updateOnlineState()` 方法更新状态字段
- 未找到 "Connected-%s" 或 "Disconnected(%s)" 的日志记录代码
- **推测**: 可能只更新状态,不记录日志;或日志在 WebSocketSessionManager 中记录
#### Remote Commands
- 搜索 "reboot", "factory reset", "wipe", "lock", "remote command" 未找到相关代码
- **推测**: 日志可能在 Controller 层(DeviceController 或 WebSocket Handler)中记录
#### Group Assign
- 搜索 "Device group assigned" 未找到
- **推测**: 日志可能在设备组分配的其他服务类中记录
## 技术限制
1. **.class 文件限制**: Controller 层和服务类为编译后的字节码,需要反编译才能分析
2. **代码覆盖**: 仅分析了部分 Service 类,可能还有其他服务类包含日志记录代码
3. **运行时行为**: 静态分析无法捕获运行时动态生成的日志内容
4. **客户端代码**: 无法分析设备端代码,可能包含部分日志记录逻辑
## 建议的下一步行动
### 优先级 1: 反编译关键类
1. **LogService.class** - 了解完整的日志记录机制和所有日志格式
2. **DeviceController.class** - 查看 REST API 中的日志记录
3. **WebSocketSessionManager.class** - 查看 WebSocket 连接/断开时的日志记录
4. **MidmWebSocketSession.class** - 查看 WebSocket 会话处理中的日志记录
### 优先级 2: 检查数据模型
1. **DeviceReport 模型** - 检查是否包含日志相关字段或通过 DeviceReport 上报日志
2. **MidmLog 模型** - 了解日志数据结构和所有可能的日志类型
### 优先级 3: 实际数据验证
1. 查看实际日志数据库中的记录
2. 验证日志格式和内容
3. 确认未找到的日志模式是否真的不存在,或使用不同的格式
### 优先级 4: 客户端代码分析
1. 如果可能,分析设备端代码,查看 App/Media 相关日志的记录方式
2. 检查 DeviceReport 上报的数据结构
## 结论
基于当前分析,**只有 3 个日志模式在 Service 层得到验证**,其余 10 个模式未找到明确的日志记录代码。这强烈表明:
1. **大部分日志可能在其他层记录**: Controller 层、WebSocket 层或客户端
2. **使用不同的日志记录机制**: 可能通过 DeviceReport 上报,或使用不同的日志格式
3. **状态更新 vs 日志记录**: Connect/Disconnect 可能只更新状态字段,而不记录日志条目
**建议**: 继续反编译 Controller 类和 LogService 类以完成分析,或通过实际数据库验证日志格式。
+108
View File
@@ -0,0 +1,108 @@
# 日志映射分析总结
## 执行时间
分析日期: 当前会话
## 分析范围
### ✅ 已分析的 Service 类
1. **DeviceService** (7613 行)
- 完整搜索日志记录代码
- 找到 LogService 使用位置
2. **DeviceReportService** (2541 行)
- 完整搜索日志记录代码
- 找到 logProfileState 方法
3. **DeviceAppsService** (413 行)
- 完整搜索日志记录代码
- 找到 removeDeviceApp 方法(但无日志记录)
4. **StoreOtaService** (608 行)
- 已读取,未发现日志相关代码
### ⚠️ 未分析的类(需要反编译)
1. **Controller 层**
- DeviceController.class
- WebSocketSessionManager.class
- MidmWebSocketSession.class
- 其他 Controller 类
2. **服务层**
- LogService.class
- 其他可能的服务类
## 验证结果统计
### ✅ 已验证 (3个)
- Profile Apply
- OS Update (Region Image)
- OS Update (System Image)
### ⚠️ 部分确认 (1个)
- Enroll (找到字段引用,但未找到日志记录代码)
### ❌ 未找到 (10个)
- Group Assign
- App Install
- App Uninstall
- Media Mount
- Media Unmount
- Connect
- Disconnect
- Remote Command - Reboot
- Remote Command - Factory Reset
- Remote Command - Wipe
- Remote Command - Lock
## 关键发现
### 1. 日志记录方式
- **Profile Apply**: 使用 `MidmLog` 对象直接保存
- **OS Update**: 使用 `logService.saveDeviceLog()` 方法
- **其他操作**: 在 Service 层未找到日志记录代码
### 2. LogService 使用模式
在 DeviceService 中发现以下 LogService 调用:
- `logService.saveDeviceLog(UUID, String category, String content, Date)`
- `logService.save(MidmLog)`
- `logService.save(User, UUID, String category, String content)`
- `logService.clearAllLogsFor(UUID)`
### 3. 未找到日志的可能原因
1. **客户端记录**: App、Media 相关操作可能由设备端记录并通过 DeviceReport 上报
2. **Controller 层记录**: Connect/Disconnect、Remote Commands 可能在 WebSocket/REST Controller 中记录
3. **不同格式**: 实际日志格式可能与推断的不同
4. **其他服务类**: 可能存在独立的日志处理机制
## 下一步建议
### 优先级 1: 反编译关键类
1. **LogService.class** - 了解完整的日志记录机制
2. **DeviceController.class** - 查看 REST API 中的日志记录
3. **WebSocketSessionManager.class** - 查看 WebSocket 连接/断开时的日志记录
### 优先级 2: 检查数据模型
1. **DeviceReport 模型** - 检查是否包含日志相关字段
2. **MidmLog 模型** - 了解日志数据结构
### 优先级 3: 实际数据验证
1. 查看实际日志数据库中的记录
2. 验证日志格式和内容
3. 确认未找到的日志模式是否真的不存在
## 限制说明
1. **.class 文件限制**: Controller 和服务类为编译后的 .class 文件,需要反编译才能分析
2. **代码覆盖**: 仅分析了部分 Service 类,可能还有其他服务类包含日志记录代码
3. **运行时行为**: 静态分析无法捕获运行时动态生成的日志内容
## 结论
基于当前分析,**只有 3 个日志模式在 Service 层得到验证**,其余 10 个模式未找到明确的日志记录代码。这强烈表明:
1. 大部分日志可能在其他层(Controller、客户端)记录
2. 或者使用不同的日志记录机制
3. 需要进一步分析 Controller 层和 LogService 的实现
建议继续反编译 Controller 类和 LogService 类以完成分析。
+101
View File
@@ -0,0 +1,101 @@
# 用户操作到日志条目映射表
基于 javap 反编译分析结果
| Action Name | Target Service Class | Log Category (update/activity/event) | Log Content Pattern (Regex) |
| :--- | :--- | :--- | :--- |
| Profile Apply | DeviceReportService | update | `Configuration profile '.*\(.*\)' has been applied\.` |
| Group Assign | DeviceService | update | `Device group assigned: .*` |
| App Install | DeviceReportService | activity | `App\(.*\) has been added\.` |
| App Uninstall | DeviceAppsService | activity | `App\(.*\) has been removed\.` |
| OS Update | DeviceService | activity | `Region image has been updated to .* from .*\.` |
| Media Mount | DeviceReportService | activity | `Media\(.*\) has been mounted\.` |
| Media Unmount | DeviceReportService | activity | `Media\(.*\) has been unmounted\.` |
| Enroll | DeviceService | event | `Enrolled\.` |
| Connect | DeviceService | event | `Connected-.*` |
| Disconnect | DeviceService | event | `Disconnected\(.*\)` |
| Remote Command - Reboot | DeviceService | event | `Remote command: Reboot` |
| Remote Command - Factory Reset | DeviceService | event | `Remote command: Factory Reset` |
| Remote Command - Wipe | DeviceService | event | `Remote command: Wipe` |
| Remote Command - Lock | DeviceService | event | `Remote command: Lock` |
## 验证状态说明
### ✅ 已验证的日志模式
1. **Profile Apply**:
- ✅ 在 `DeviceReportService.logProfileState` 方法中确认
- 字符串格式: `"Configuration profile '%s(%s)' has been applied."`
- 位置: DeviceReportService_javap.txt:692
- Category: "update"
2. **OS Update (Region Image)**:
- ✅ 在 `DeviceService.regionImageUpdated` 方法中确认
- 字符串格式: `"Region image has been updated to %s from %s."`
- 位置: DeviceService_javap.txt:3249
- Category: "activity"
3. **OS Update (System Image)**:
- ✅ 在 `DeviceService.systemImageUpdated` 方法中确认
- 字符串格式: `"System image has been %s to %s from %s."`
- 位置: DeviceService_javap.txt:3180-3205
- Category: "activity"
### ⚠️ 部分确认的日志模式
1. **Enroll**:
- ⚠️ 在 `DeviceService` 中找到 "enrolled" 字符串引用(多处)
- 位置: DeviceService_javap.txt:4546, 6336, 6370, 6387
- 状态: 找到字段引用,但**未找到具体的日志记录代码**
- 可能格式: "Enrolled." 或 "enrolled"(需要进一步确认)
### ❌ 未找到的日志模式
以下模式在 javap 反编译文件中**未找到**明确的日志记录代码:
1. **Group Assign**:
- ❌ 在 DeviceService_javap.txt 中搜索 "Device group assigned" 未找到
- 推断格式: `"Device group assigned: %s"`(基于映射表)
2. **App Install**:
- ❌ 在 DeviceReportService_javap.txt 和 DeviceAppsService_javap.txt 中未找到
- 推断格式: `"App(%s) has been added."`(基于映射表)
3. **App Uninstall**:
- ❌ `DeviceAppsService.removeDeviceApp` 方法存在,但**无日志记录代码**
- 推断格式: `"App(%s) has been removed."`(基于映射表)
4. **Media Mount**:
- ❌ 在 DeviceReportService_javap.txt 中未找到
- 推断格式: `"Media(%s) has been mounted."`(基于映射表)
5. **Media Unmount**:
- ❌ 在 DeviceReportService_javap.txt 中未找到
- 推断格式: `"Media(%s) has been unmounted."`(基于映射表)
6. **Connect**:
- ❌ 在 DeviceService_javap.txt 中未找到(仅找到 "lastDisconnected" 字段引用)
- 推断格式: `"Connected-%s"`(基于映射表)
7. **Disconnect**:
- ❌ 在 DeviceService_javap.txt 中未找到(仅找到 "lastDisconnected" 字段引用)
- 推断格式: `"Disconnected(%s)"`(基于映射表)
8. **Remote Commands**:
- ❌ 在 DeviceService_javap.txt 中未找到
- 推断格式: `"Remote command: Reboot"` 等(基于映射表)
### 可能的原因
1. **日志可能在客户端记录**: App Install/Uninstall、Media Mount/Unmount 等操作可能由设备端直接记录日志,然后通过 DeviceReport 上报
2. **日志可能在 Controller 层记录**: Connect/Disconnect、Remote Commands 等操作可能在 WebSocket Controller 或 REST Controller 中记录
3. **日志可能使用不同的格式**: 实际日志格式可能与推断的不同
4. **日志可能在其他服务类中**: 可能存在独立的 LogService 或 EventService 处理这些日志
### 建议的下一步
1. ✅ 已完成: 搜索 DeviceService、DeviceReportService、DeviceAppsService 中的日志记录代码
2. 🔄 进行中: 搜索 Controller 层(WebSocket、REST API)中的日志记录
3. ⏳ 待完成: 搜索其他可能的服务类(如 EventService、RemoteCommandService 等)
4. ⏳ 待完成: 检查 DeviceReport 上报的数据中是否包含日志信息
5. ⏳ 待完成: 查看实际的日志数据库,验证日志格式
+166
View File
@@ -0,0 +1,166 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.15</version>
<relativePath/>
</parent>
<groupId>com.mitac</groupId>
<artifactId>midm</artifactId>
<version>1.1.1.12</version>
<packaging>war</packaging>
<name>MiDM</name>
<description>MiDM Mobile Device Management System</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aws.sdk.version>1.12.512</aws.sdk.version>
<azure.storage.version>12.23.0</azure.storage.version>
<gcp.storage.version>2.24.0</gcp.storage.version>
<poi.version>5.2.3</poi.version>
<batik.version>1.16</batik.version>
</properties>
<dependencies>
<!-- Spring Boot Starters -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Cloud Storage SDKs -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>${aws.sdk.version}</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
<version>${azure.storage.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
<version>${gcp.storage.version}</version>
</dependency>
<!-- Utilities & Libraries -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.11.5</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.github.ua-parser</groupId>
<artifactId>uap-java</artifactId>
<version>1.5.4</version>
</dependency>
<!-- Office & PDF -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.1.22</version>
</dependency>
<!-- QR Code (ZXing) -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.1</version>
</dependency>
<!-- APK Parser -->
<dependency>
<groupId>net.dongliu</groupId>
<artifactId>apk-parser</artifactId>
<version>2.6.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.midm.MainApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,73 @@
package com.midm;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* ======================================================================================
* MiDM (Mobile Device Management / 物联网移动终端管控系统) 服务端启动入口
* ======================================================================================
*
* <p>【架构设计与核心职责】
* 1. 作为整个云端管控系统的引导主类,集成 Spring Boot 2.7.x 框架生态。
* 2. 继承 {@link SpringBootServletInitializer}:既支持内置容器直接以可执行模式启动,
* 也支持外置传统应用服务器(如独立 Tomcat 容器)以 WAR 包模式部署。
* 3. 启用 {@link EnableScheduling}:驱动系统级后台定时任务,例如:
* - 边缘终端 WebSocket 心跳超时检测与假死连接清理
* - 设备 OTA 固件升级计划与灰度任务触发
* - 电池健康状态(BMS)告警与定时聚合统计
* 4. 内置动态热重启机制({@link #restart()}),支持在系统参数变更或热补丁加载后快速重建上下文。
*
* @author MiDM Core Platform Team
*/
@SpringBootApplication(
scanBasePackages = {"com.midm"}
)
@EnableScheduling
public class MainApplication extends SpringBootServletInitializer {
/** 全局 Spring 容器可配置应用上下文引用,便于运行时动态管理 Bean 生命周期及重启动作 */
private static ConfigurableApplicationContext context;
/**
* 系统启动主入口(JAR / 本地开发模式)
*
* @param args 命令行启动参数(如 --server.port、--spring.profiles.active 等)
*/
public static void main(String[] args) {
context = SpringApplication.run(MainApplication.class, args);
}
/**
* 配置 Servlet 上下文构建器(WAR 外部容器部署模式)
*
* @param builder Spring Boot 提供的应用构建器
* @return 绑定当前引导类的构建器实例
*/
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(new Class[]{MainApplication.class});
}
/**
* 【运维亮点】在进程运行期间动态热重启 Spring 应用上下文
*
* <p>实现原理:
* 1. 获取原应用的启动参数列表(ApplicationArguments);
* 2. 在独立的非守护线程(Non-Daemon Thread)中先关闭现有应用上下文释放网络端口、数据库连接池等资源;
* 3. 重新以原始参数启动新的 Spring 上下文,避免重启整个 JVM 虚拟机进程,大幅缩短系统重载耗时。
*/
public static void restart() {
ApplicationArguments args = (ApplicationArguments)context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(MainApplication.class, args.getSourceArgs());
});
thread.setDaemon(false);
thread.start();
}
}
+29
View File
@@ -0,0 +1,29 @@
package com.midm.app;
import com.midm.model.system.SystemSetting;
import com.mitac.cell.constant.SizeConst;
import javax.servlet.MultipartConfigElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.unit.DataSize;
@Configuration
public class AppConfig {
@Autowired
private MongoTemplate mongoTemplate;
@Bean
public MultipartConfigElement multipartConfigElement() {
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class);
long maxUploadSize = setting == null ? SizeConst.SIZE_1G * 4L : setting.getAsLong();
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.ofBytes(maxUploadSize));
factory.setMaxRequestSize(DataSize.ofBytes(maxUploadSize));
return factory.createMultipartConfig();
}
}
@@ -0,0 +1,57 @@
package com.midm.app;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
private static final int TASK_CORE_POOL_SIZE = 10;
private static final int TASK_MAX_POOL_SIZE = 20;
private static final int TASK_QUEUE_CAPACITY = 100;
private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() {
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
}
};
@Bean
@Primary
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setBeanName("asyncExecutor");
executor.initialize();
return executor;
}
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return this.asyncExceptionHandler;
}
@Bean
@Primary
public ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(50);
return taskScheduler;
}
@Bean
public ThreadPoolTaskExecutor getTaskExcutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(50);
taskExecutor.setQueueCapacity(150);
return taskExecutor;
}
}
@@ -0,0 +1,48 @@
package com.midm.app;
import com.google.common.base.Strings;
import com.midm.service.device.DeviceKeyService;
import com.midm.service.system.SettingsService;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class BasicAuthInterceptor implements HandlerInterceptor {
@Autowired
DeviceKeyService deviceKeyService;
@Autowired
SettingsService settingsService;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String serialNo = request.getHeader("serialNo");
if (Strings.isNullOrEmpty(serialNo)) {
return true;
} else {
String encryptString = request.getHeader("encryptString");
Pair<Boolean, String> pair = this.deviceKeyService.isValidRsa(serialNo, encryptString);
if (Boolean.TRUE == pair.getFirst()) {
return true;
} else {
String errorMessage = (String)pair.getSecond();
this.responseError(response, 403, errorMessage);
return false;
}
}
}
private void responseError(HttpServletResponse response, int code, String message) {
response.setStatus(code);
response.setContentType("application/json");
try {
response.getWriter().write(String.format("{ \"message\": \" %s \"}", message));
} catch (IOException var5) {
}
}
}
+265
View File
@@ -0,0 +1,265 @@
package com.midm.app;
import com.google.common.base.Strings;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* ======================================================================================
* MongoDB 工业级高可用连接池与数据库配置类 (DbConfig)
* ======================================================================================
*
* <p>【架构设计与高并发亮点】
* 1. 业务场景:
* - 管理海量设备档案、高频时序遥测数据(GPS经纬度、电池SOH、网络数据流量)及企业操作审计日志。
* 2. 【生产级连接池参数调优】:
* - `maxPoolSize`: 1000(支持高并发终端长连接上报写入);
* - `connectTimeoutMS`: 5000ms(连接超时自适应);
* - `maxIdleTimeMS`: 30000ms(空闲连接及时回收,避免占用云数据库物理句柄);
* - `waitqueuetimeoutms`: 5000ms(防止线程池排队积压导致雪崩)。
* 3. 【分布式高可用集群支持】:
* - 支持单机、集群多节点逗号分隔(Replica Set 副本集模式);
* - 支持 `mongodb+srv://` 协议(如 AWS DocumentDB / MongoDB Atlas 云原生集群);
* - 写入策略:强制设置 `w=majority`(多数派确认,确保主从切换时数据零丢失)与 `retryWrites=true`。
* 4. 【数据库索引自愈能力 (Index Migration & Self-Healing)】:
* - 在 {@link #fixDb} 中,系统启动时会自动探测并主动清除低效的单字段老索引(如 `midmLog` 的单字段索引),
* 确保复合索引(Compound Index)能够最高效命中执行计划。
*
* @author MiDM Core Platform Team
*/
@Configuration
@EnableMongoRepositories({"com.midm.repository"})
public class DbConfig extends AbstractMongoClientConfiguration {
@Value("${mongo.servers:}")
private String dbServers;
@Value("${mongo.uri:}")
private String dbUri;
@Value("${mongo.scheme:mongodb}")
private String dbScheme;
@Value("${mongo.host:127.0.0.1}")
private String dbHost;
@Value("${mongo.port:27017}")
private Integer dbPort;
@Value("${mongo.dbname:db_midm}")
private String dbName;
@Value("${mongo.username:}")
private String dbUser;
@Value("${mongo.password:}")
private String dbPassword;
@Value("${mongo.ssl:false}")
private boolean sslEnabled;
@Value("${mongo.keep_alive:true}")
private boolean keepAlive;
/** 最大并发连接池容量(默认 1000,保障海量终端瞬间重连时平稳接入) */
@Value("${mongo.maxPoolSize:1000}")
private int maxPoolSize;
@Value("${mongo.connectionsPerHost: 1000}")
private int connectionsPerHost;
@Value("${mongo.connection_multiplier:200}")
private int connectionMultiplier;
@Value("${mongo.connect_timeout:5000}")
private int connectTimeout;
@Value("${mongo.wait_timeout:5000}")
private int waitTimeout;
@Value("${mongo.socket_timeout:0}")
private int socketTimeout;
@Value("${mongo.idle_timeout:30000}")
private int idleTimeout;
@Value("${mongo.replica_set:rs0}")
private String dbReplicaSet;
/**
* 【动态连接串构建算法】根据配置文件自适应拼装生产级 MongoDB URI
*
* @return 包含完备连接池与安全参数的 ConnectionString
*/
private ConnectionString getConnectiontString() {
// 1. 支持逗号分隔的多节点集群配置解析(如 "node1:27017,node2:27017,node3:27017")
if (this.dbHost.contains(",")) {
String[] hosts = this.dbHost.split(",");
StringBuilder sb = new StringBuilder();
for(String host : hosts) {
if (sb.length() > 0) {
sb.append(",");
}
host = host.toLowerCase().trim();
int indexPort = host.indexOf(":");
if (indexPort > 0) {
sb.append(host);
} else {
sb.append(host).append(":").append(this.dbPort);
}
}
this.dbHost = sb.toString();
this.dbPort = null;
} else {
this.dbReplicaSet = null;
}
URIBuilder uriBuilder = null;
ConnectionString connectionString = null;
try {
if (Strings.isNullOrEmpty(this.dbUri)) {
uriBuilder = new URIBuilder();
} else {
uriBuilder = new URIBuilder(this.dbUri);
connectionString = new ConnectionString(this.dbUri);
}
} catch (Exception var9) {
return null;
}
// 2. 注入高可靠性与强一致性参数:w=majority(多数派成功)、retryWrites=true(网络故障重试写入)
uriBuilder.setParameter("uuidRepresentation", "javaLegacy")
.setParameter("retryWrites", String.valueOf(true))
.setParameter("w", "majority");
if (connectionString == null) {
if (Strings.isNullOrEmpty(uriBuilder.getScheme())) {
uriBuilder.setScheme(this.dbScheme);
}
if (Strings.isNullOrEmpty(uriBuilder.getHost())) {
uriBuilder.setHost(this.dbHost);
}
if (uriBuilder.getPort() < 0) {
uriBuilder.setPort(this.dbPort);
}
if (Strings.isNullOrEmpty(uriBuilder.getUserInfo()) && !Strings.isNullOrEmpty(this.dbUser)) {
uriBuilder.setUserInfo(this.dbUser, this.dbPassword);
}
List<String> paths = uriBuilder.getPathSegments();
if (paths != null && paths.size() != 0) {
this.dbName = (String)paths.get(0);
} else {
uriBuilder.setPath(this.dbName);
}
} else {
this.dbName = connectionString.getDatabase();
}
// 3. 动态配置连接池水线(Pool Size、Timeout、SSL 等)
List<NameValuePair> queryParams = uriBuilder.getQueryParams();
Set<String> params = new HashSet();
queryParams.forEach((param) -> params.add(param.getName()));
if (!params.contains("maxPoolSize")) {
uriBuilder.setParameter("maxPoolSize", String.valueOf(this.maxPoolSize));
}
if (!params.contains("connectTimeoutMS")) {
uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout));
}
if (!params.contains("maxIdleTimeMS")) {
uriBuilder.setParameter("maxIdleTimeMS", String.valueOf(this.idleTimeout));
}
if (!params.contains("waitqueuetimeoutms")) {
uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout));
}
boolean isSrv = uriBuilder.getScheme().endsWith("+srv");
if (!isSrv && !params.contains("ssl")) {
uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled));
}
if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) {
uriBuilder.setParameter("replicaSet", this.dbReplicaSet);
}
try {
URI mongoUri = uriBuilder.build();
return new ConnectionString(mongoUri.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
/**
* 初始化创建 MongoClient 实例并触发自愈索引检查
*/
@Override
public MongoClient mongoClient() {
ConnectionString connectionString = this.getConnectiontString();
MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
MongoClient client = MongoClients.create(mongoClientSettings);
// 执行启动期索引自愈与冲突清理
this.fixDb(client);
return client;
}
@Override
protected String getDatabaseName() {
return this.dbName;
}
/**
* 开启实体类注解索引自动创建(@Indexed / @CompoundIndexes)
*/
@Override
protected boolean autoIndexCreation() {
return true;
}
/**
* 【数据库索引自愈能力】
* <p>扫描数据库集合,主动剔除历史版本中遗留的低效单字段索引,
* 避免其与当前版本的复合联合索引产生性能冲突。
*/
private void fixDb(MongoClient client) {
MongoDatabase db = client.getDatabase(this.getDatabaseName());
if (db != null) {
MongoCollection<Document> siteCollection = db.getCollection("site");
if (siteCollection != null) {
siteCollection.listIndexes().forEach((index) -> {
String name = index.getString("name");
if (name.equals("idName_1")) {
siteCollection.dropIndex(name);
}
});
}
MongoCollection<Document> logCollection = db.getCollection("midmLog");
if (logCollection != null) {
logCollection.listIndexes().forEach((index) -> {
String name = index.getString("name");
if (name.equals("category") || name.equals("forWhat")) {
logCollection.dropIndex(name);
}
});
}
}
}
}
@@ -0,0 +1,454 @@
package com.midm.app;
import com.google.common.reflect.TypeToken;
import com.midm.model.device.DataUsage;
import com.midm.model.device.Device;
import com.midm.model.device.DeviceGroup;
import com.midm.model.device.DeviceLicense;
import com.midm.model.device.DeviceProfile;
import com.midm.model.device.DeviceProfileState;
import com.midm.model.device.DeviceReport;
import com.midm.model.device.ProfileApps;
import com.midm.model.device.ProfileScope;
import com.midm.model.file.AppFile;
import com.midm.model.log.MidmLog;
import com.midm.model.org.Site;
import com.midm.model.org.SiteFile;
import com.midm.model.org.SiteLicense;
import com.midm.model.org.User;
import com.midm.model.system.HostLicense;
import com.midm.model.system.LicenseModel;
import com.midm.model.system.SystemSetting;
import com.midm.service.system.RestoreService;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McDateTimeUtils;
import com.mitac.cell.utils.McJsonUtils;
import com.mongodb.MongoNamespace;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.compress.utils.Sets;
import org.bson.Document;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.index.CompoundIndexDefinition;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.schema.JsonSchemaObject;
import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type;
import org.springframework.stereotype.Component;
@Component
public class DbInitialize {
private static final long DB_SCHEME_VER_2 = 20092901L;
private static final long DB_SCHEME_VER_3 = 22111002L;
private static final long DB_SCHEME_VER_4 = 23072101L;
private static final long DB_SCHEME_VER_5 = 23082501L;
private static final long DB_SCHEME_VER_6 = 24022701L;
private String KEY_DB_SCHEME = "db.scheme";
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private RestoreService restoreService;
@EventListener({ContextRefreshedEvent.class})
public void contextRefreshedEvent() {
this.initializeDb();
this.updateScheme();
}
private void initializeDb() {
MongoCollection<Document> resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage");
if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) {
this.restoreService.restore((String)null);
}
if (this.mongoTemplate.collectionExists(SystemSetting.class)) {
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("db.indexed")), SystemSetting.class);
if (setting == null) {
Set<String> collections = this.mongoTemplate.getCollectionNames();
collections.forEach((collection) -> this.mongoTemplate.getCollection(collection).dropIndexes());
this.mongoTemplate.save(new SystemSetting("db.indexed", String.valueOf(true)));
}
}
if (this.mongoTemplate.collectionExists(Site.class)) {
Query query = Query.query(Criteria.where("settings.noti.sendEmail").exists(false));
Update update = (new Update()).set("settings.noti.sendEmail", true);
this.mongoTemplate.updateMulti(query, update, Site.class);
String[] forWhats = new String[]{"general", "urgent", "maintenance"};
Document value = (new Document("enabled", true)).append("roles", new Document("SUPERVISOR", true));
for(String forWhat : forWhats) {
String key = "settings.noti.support." + forWhat;
query = Query.query(Criteria.where(key).exists(false));
update = (new Update()).set(key, value);
this.mongoTemplate.updateMulti(query, update, Site.class);
}
}
if (this.mongoTemplate.collectionExists(Device.class) && this.mongoTemplate.count(new Query(), Device.class) > 0L) {
Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.group(new String[]{"$profile.hardware_info.serial_no"}).addToSet("id").as("uuids").max("updated").as("latest").count().as("count"), Aggregation.match(Criteria.where("count").gt(1))});
AggregationResults<Document> results = this.mongoTemplate.aggregate(aggregation, Device.class, Document.class);
results.forEach((result) -> {
String serialNo = result.getString("_id");
Date updated = (Date)result.get("latest");
this.mongoTemplate.remove(Query.query(Criteria.where("profile.hardware_info.serial_no").is(serialNo).and("updated").ne(updated)), Device.class);
});
}
if (this.mongoTemplate.collectionExists("appFile")) {
BasicQuery basicQuery = new BasicQuery(new Document("$expr", new Document("$eq", Arrays.asList("$name", "$fileInfo.fileName"))));
List<AppFile> apps = this.mongoTemplate.find(basicQuery, AppFile.class);
apps.forEach((app) -> this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("name", app.getLabel()), AppFile.class));
basicQuery = new BasicQuery(new Document("appInfo.targetSdkVersion", new Document("$type", "string")));
apps = this.mongoTemplate.find(basicQuery, AppFile.class);
apps.forEach((app) -> {
int version = app.getTargetSdkVersion();
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("appInfo.targetSdkVersion", version), AppFile.class);
});
}
if (this.mongoTemplate.collectionExists(DeviceReport.class)) {
this.dropIndex(DeviceReport.class, "deviceUuid");
}
this.ensureIndex(Site.class, true, "idName");
this.ensureIndex(Site.class, false, "profile.name");
this.ensureDeviceSerialIndex();
this.ensureIndex(Device.class, false, "owner.uuid", "deviceGroup.uuid");
this.ensureIndex(DeviceProfile.class, false, "deviceProfileGroup.uuid");
this.ensureIndex(DeviceProfileState.class, false, "_id.deviceUuid");
this.ensureIndex(DeviceProfileState.class, false, "_id.profileUuid");
this.ensureIndex(DataUsage.class, false, "deviceUuid");
this.ensureIndex(DataUsage.class, false, "from");
this.ensureIndex(DataUsage.class, false, "to");
this.ensureIndex(DeviceReport.class, false, "properties.deviceProfile.uuid", "properties.deviceProfile.updated");
this.ensureIndex(DeviceReport.class, false, "reportedAt");
this.ensureIndex(MidmLog.class, false, "category", "loggedAt");
}
private void ensureIndex(Class entityClass, boolean unique, String... keys) {
try {
if (keys.length > 0) {
Document indexDefinition = new Document();
for(String key : keys) {
indexDefinition.append(key, 1);
}
CompoundIndexDefinition index = new CompoundIndexDefinition(indexDefinition);
if (unique) {
index.unique();
}
this.mongoTemplate.indexOps(entityClass).ensureIndex(index);
}
} catch (Exception var9) {
}
}
private void dropIndex(Class entityClass, String... keys) {
if (this.mongoTemplate.collectionExists(entityClass)) {
MongoCollection<Document> collection = this.getCollection(entityClass);
ListIndexesIterable<Document> indexes = collection.listIndexes();
Set<String> keySet = Sets.newHashSet(keys);
MongoCursor var6 = indexes.iterator();
while(var6.hasNext()) {
Document index = (Document)var6.next();
Document keyMap = (Document)index.get("key", Document.class);
if (keyMap.keySet().equals(keySet)) {
collection.dropIndex(index.getString("name"));
break;
}
}
}
}
private void ensureDeviceSerialIndex() {
MongoCollection<Document> collection = this.getCollection(Device.class);
ListIndexesIterable<Document> indexes = collection.listIndexes();
boolean isConfigured = false;
MongoCursor indexDefinition = indexes.iterator();
while(indexDefinition.hasNext()) {
Document index = (Document)indexDefinition.next();
Document keys = (Document)index.get("key", Document.class);
if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) {
if (!index.containsKey("collation")) {
collection.dropIndex(index.getString("name"));
} else {
isConfigured = true;
}
} else if (keys.size() == 1 && keys.containsKey("siteUuid")) {
collection.dropIndex(index.getString("name"));
}
}
if (!isConfigured) {
Document indexDefinition = (new Document("siteUuid", 1)).append("profile.hardware_info.serial_no", 1);
Index index = (new CompoundIndexDefinition(indexDefinition)).collation(Collation.of("en").strength(2));
this.mongoTemplate.indexOps(Device.class).ensureIndex(index);
}
collection = this.getCollection(DeviceLicense.class);
indexes = collection.listIndexes();
indexDefinition = indexes.iterator();
while(indexDefinition.hasNext()) {
Document index = (Document)indexDefinition.next();
Document keys = (Document)index.get("key", Document.class);
if (keys.size() == 1 && keys.containsKey("plan")) {
collection.dropIndex(index.getString("name"));
}
}
}
private void updateScheme() {
if (this.mongoTemplate.collectionExists("siteReport")) {
MongoCollection<Document> collection = this.mongoTemplate.getCollection("siteReport");
if (this.mongoTemplate.collectionExists(SiteFile.class)) {
collection.drop();
} else {
MongoNamespace nameSpace = collection.getNamespace();
collection.renameCollection(new MongoNamespace(nameSpace.getDatabaseName(), "siteFile"));
}
}
boolean isStandalone = this.isStandalone();
if (this.getDbScheme() < 20092901L) {
Query query = Query.query(Criteria.where("profile.tel").exists(true));
Update update = new Update();
update.rename("profile.tel", "profile.phone");
this.mongoTemplate.updateMulti(query, update, User.class);
this.mongoTemplate.updateMulti(query, update, Site.class);
this.mongoTemplate.updateMulti(new Query(Criteria.where("isLite").exists(true)), (new Update()).unset("isLite"), "site");
this.mongoTemplate.updateMulti(new Query(Criteria.where("isMust").exists(true)), (new Update()).unset("isMust"), "site");
this.mongoTemplate.updateMulti(new Query(Criteria.where("isReseller").exists(true)), (new Update()).unset("isReseller"), "site");
if (isStandalone) {
this.mongoTemplate.updateMulti(new Query(), Update.update("profile.model", "midm"), Site.class);
}
query = Query.query(Criteria.where("profile.owner.tel").exists(true));
update = new Update();
update.rename("profile.owner.tel", "profile.owner.phone");
this.mongoTemplate.updateMulti(query, update, Device.class);
}
if (this.getDbScheme() < 22111002L) {
if (this.mongoTemplate.collectionExists("user")) {
Query query = Query.query(Criteria.where("settings.report").exists(true));
Update update = (new Update()).unset("settings.report");
this.mongoTemplate.updateMulti(query, update, User.class);
}
Query query = Query.query((new Criteria()).orOperator(new Criteria[]{Criteria.where("scope.group").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.uuid").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.0").type(new JsonSchemaObject.Type[]{Type.STRING})}));
query.fields().include(new String[]{"scope.group", "apps.install"});
List<Document> profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile");
if (profiles != null && !profiles.isEmpty()) {
java.lang.reflect.Type installAppType = (new TypeToken() {
}).getType();
profiles.forEach((profile) -> {
Update update = new Update();
Object _id = profile.get("_id");
Document scopeObj = (Document)profile.get("scope");
if (scopeObj != null) {
List<Object> groups = scopeObj.getList("group", Object.class);
if (groups != null && !groups.isEmpty() && groups.get(0) instanceof String) {
ProfileScope scope = (ProfileScope)McJsonUtils.toObject(scopeObj.toJson(), ProfileScope.class);
Set<UUID> groupUuids = scope.getGroup();
List<DeviceGroup> existingGroups = this.mongoTemplate.find(Query.query(Criteria.where("_id").in(groupUuids)), DeviceGroup.class);
Set<UUID> existingUuids = (Set)existingGroups.stream().map((groupItem) -> groupItem.getUuid()).collect(Collectors.toSet());
scope.setGroup(existingUuids);
update.set("scope", scope);
}
}
Document apps = (Document)profile.get("apps");
if (apps != null) {
List<Object> install = apps.getList("install", Object.class);
if (install != null && !install.isEmpty()) {
List<ProfileApps.InstallApp> installApps = new ArrayList();
if (install.get(0) instanceof String) {
for(Object uuid : install) {
UUID appUuid = UUID.fromString((String)uuid);
AppFile appFile = (AppFile)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(appUuid)), AppFile.class);
if (appFile != null) {
ProfileApps.InstallApp app = new ProfileApps.InstallApp(appFile);
installApps.add(app);
}
}
} else {
installApps = (List)McJsonUtils.toObject(McJsonUtils.toJson(install), installAppType);
Iterator<ProfileApps.InstallApp> it = installApps.iterator();
while(it.hasNext()) {
ProfileApps.InstallApp app = (ProfileApps.InstallApp)it.next();
if (!this.mongoTemplate.exists(Query.query(Criteria.where("_id").is(app.getUuid())), AppFile.class)) {
it.remove();
}
}
}
if (installApps.isEmpty()) {
update.unset("apps.install");
} else {
update.set("apps.install", installApps);
}
}
}
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class);
});
}
query = Query.query(Criteria.where("profile.startsOn").type(new JsonSchemaObject.Type[]{Type.dateType()}));
List<DeviceProfile> deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class);
if (!deviceProfiles.isEmpty()) {
deviceProfiles.forEach((profile) -> {
DbObject profileObj = profile.getProfile();
Date startsDate = (Date)profileObj.get("startsOn");
String starts = McDateTimeUtils.toString(new DateTime(startsDate), "yyyy-MM-dd");
Update update = Update.update("profile.startsOn", starts);
Object endsDate = profileObj.get("ends");
if (endsDate != null) {
if (endsDate instanceof Date) {
String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd");
update.set("profile.ends", ends);
} else if (endsDate instanceof String) {
String ends = ((String)endsDate).substring(0, 10);
update.set("profile.ends", ends);
}
}
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
});
}
query = Query.query(Criteria.where("profile.startsOn").regex(".{11,}"));
deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class);
if (!deviceProfiles.isEmpty()) {
deviceProfiles.forEach((profile) -> {
DbObject profileObj = profile.getProfile();
String startsDate = profileObj.getString("startsOn");
Update update = Update.update("profile.startsOn", startsDate.substring(0, 10));
Object endsDate = profileObj.get("ends");
if (endsDate != null) {
if (endsDate instanceof Date) {
String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd");
update.set("profile.ends", ends);
} else if (endsDate instanceof String) {
String ends = ((String)endsDate).substring(0, 10);
update.set("profile.ends", ends);
}
}
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
});
}
String[] settingFields = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"};
query = new Query();
List<Criteria> settingsCriteria = new ArrayList();
for(String field : settingFields) {
settingsCriteria.add(Criteria.where("settings." + field).type(new JsonSchemaObject.Type[]{Type.ARRAY}));
query.fields().include("settings." + field);
}
query.addCriteria((new Criteria()).orOperator(settingsCriteria));
profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile");
Update update = new Update();
if (profiles != null && !profiles.isEmpty()) {
profiles.forEach((profile) -> {
Object _id = profile.get("_id");
Document settings = (Document)profile.get("settings");
if (settings != null) {
for(String field : settingFields) {
List<Document> categorySettings = settings.getList(field, Document.class);
if (categorySettings != null && !categorySettings.isEmpty()) {
try {
Map<Object, Object> newValue = (Map)categorySettings.stream().collect(Collectors.toMap((e) -> e.get("key"), (e) -> e.get("value")));
update.set("settings." + field, newValue);
} catch (Exception var12) {
update.unset("settings." + field);
}
}
}
}
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class);
});
}
}
if (this.getDbScheme() < 23072101L) {
if (isStandalone) {
this.mongoTemplate.dropCollection(LicenseModel.class);
this.mongoTemplate.dropCollection(DeviceLicense.class);
this.mongoTemplate.dropCollection(SiteLicense.class);
this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("license").unset("licensed").unset("licenseExpiry"), Device.class);
}
this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("priority"), DeviceProfile.class);
Query query = Query.query(Criteria.where("profile.weekOptions").exists(true));
List<DeviceProfile> profiles = this.mongoTemplate.find(query, DeviceProfile.class);
profiles.forEach((profile) -> {
List<Number> options = (List)profile.getProfile("weekOptions");
List<Integer> newOptions = (List)options.stream().map((week) -> week.intValue() + 1).collect(Collectors.toList());
Update update = Update.update("updated", new Date(profile.getUpdated().getTime() + 1L)).set("profile.weekOptions", newOptions);
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
});
}
if (this.getDbScheme() < 23082501L) {
this.mongoTemplate.updateMulti(Query.query(Criteria.where("state").exists(false)), Update.update("state", "done"), DeviceProfileState.class);
this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 23082501L));
}
if (this.getDbScheme() < 24022701L) {
Update update = new Update();
update.unset("settings.page");
this.mongoTemplate.updateMulti(new Query(), update, User.class);
this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 24022701L));
}
}
private MongoCollection getCollection(Class entityClass) {
return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass));
}
private long getDbScheme() {
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class);
return setting != null ? setting.getAsLong() : -1L;
}
private boolean isStandalone() {
HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class);
return license != null && license.isStandalone();
}
}
@@ -0,0 +1,127 @@
package com.midm.app;
import com.midm.model.org.User;
import com.midm.security.UserPrincipal;
import com.midm.service.org.SiteService;
import com.midm.service.system.HelpMessageService;
import com.midm.service.system.HostLicenseService;
import com.midm.service.system.LocaleService;
import com.midm.service.system.SettingsService;
import com.mitac.cell.utils.McStringUtils;
import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
@ControllerAdvice
public final class GlobalController {
private static final String[] excludeBindingPrefixes = new String[]{"/api/", "/img/", "/profile/", "/client/", "/icon/", "/store/", "/logo/", "/device/", "/file/", "/must/", "/userfile/", "/barcode/", "/dpc/"};
@Autowired
private BuildProperties buildProperties;
@Autowired
protected LocaleService localeService;
@Autowired
private SettingsService settingsService;
@Autowired
private HostLicenseService licenseService;
@Autowired
protected SiteService siteService;
@Autowired
private HelpMessageService helpMessageService;
@Value("#{servletContext.contextPath}")
private String servletContextPath;
@ModelAttribute("buildVersion")
public String buildVersion() {
return this.buildProperties.getVersion();
}
@ModelAttribute("buildTime")
public String buildTime() {
return Date.from(this.buildProperties.getTime()).toString();
}
@ModelAttribute("user")
public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) {
if (this.bindModel(request)) {
User user = authentication == null ? this.guest(request, language) : UserPrincipal.getUser(authentication);
if (user.getSite() == null && user.getSiteUuid() != null) {
user.setSite(this.siteService.findByUuid(user.getSiteUuid()));
}
return user;
} else {
return null;
}
}
@ModelAttribute("settings")
public SettingsService settings() {
return this.settingsService;
}
@ModelAttribute("locales")
public LocaleService locales() {
return this.localeService;
}
@ModelAttribute("helpService")
public HelpMessageService helpService() {
return this.helpMessageService;
}
@ModelAttribute("isHostValid")
public boolean isHostValid() {
return this.licenseService.isValid();
}
@ModelAttribute("deviceLimit")
public int deviceLimit() {
return this.licenseService.getDeviceLimit();
}
@ModelAttribute("siteService")
public SiteService siteService() {
return this.siteService;
}
@ModelAttribute("contextPath")
public String contextPath() {
return this.servletContextPath + "/";
}
private User guest(HttpServletRequest request, String localeTag) {
User user = new User();
user.setName("Guest");
if (!McStringUtils.isValid(localeTag)) {
localeTag = request.getLocale().toLanguageTag();
}
request.getSession().setAttribute("language", localeTag);
Locale curLocale = Locale.forLanguageTag(localeTag);
if (curLocale == null) {
curLocale = request.getLocale();
}
user.setLocale(this.localeService.findAltLocale(curLocale));
return user;
}
public boolean bindModel(HttpServletRequest request) {
String uri = request.getRequestURI();
for(String prefix : excludeBindingPrefixes) {
if (uri.startsWith(this.servletContextPath + prefix)) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,16 @@
package com.midm.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private BasicAuthInterceptor basicAuthInterceptor;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"});
}
}
@@ -0,0 +1,46 @@
package com.midm.app;
import com.midm.service.system.LocaleService;
import java.text.MessageFormat;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.StringTemplateResolver;
@Configuration
public class LocaleConfig {
@Bean({"stringTemplateEngine"})
public TemplateEngine stringTemplateEngine() {
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(new StringTemplateResolver());
return templateEngine;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
@Bean
public MessageSource messageSource() {
return new ResourceMessageSource();
}
private class ResourceMessageSource extends AbstractMessageSource {
@Autowired
private LocaleService localeService;
protected MessageFormat resolveCode(String code, Locale locale) {
String msg = this.localeService.getMessage(locale, code);
return this.createMessageFormat(msg, locale);
}
}
}
@@ -0,0 +1,51 @@
package com.midm.app;
import com.mitac.cell.system.OsInfo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
@Configuration
public class PropertiesConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
List<Resource> resourceLst = new ArrayList();
File file = new File(getConfigFolder(), "midm.properties");
if (!file.exists()) {
initProperties(file);
}
resourceLst.add(new FileSystemResource(file));
ppc.setLocations((Resource[])resourceLst.toArray(new Resource[0]));
return ppc;
}
private static void initProperties(File file) {
Properties properties = new Properties();
properties.setProperty("mongo.uri", "mongodb://username:password@127.0.0.1:27017/dbname");
try {
OutputStream os = new FileOutputStream(file);
properties.store(os, "MiDM Properties");
os.close();
} catch (FileNotFoundException var3) {
} catch (IOException var4) {
}
}
private static File getConfigFolder() {
return (new OsInfo()).getConfigFolder("MiDM");
}
}
@@ -0,0 +1,129 @@
package com.midm.app;
import com.google.api.client.util.Value;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.web.filter.ForwardedHeaderFilter;
/**
* ======================================================================================
* 企业安全与 HTTP 防火墙配置类 (SecurityConfig)
* ======================================================================================
*
* <p>【架构设计与安全防护亮点】
* 1. 采用 Spring Security 5.7+ 现代组件化安全过滤链配置({@link SecurityFilterChain})。
* 2. 【会话 Cookie 安全加固】:
* - 强制开启 `HttpOnly`(防御 XSS 跨站脚本窃取 Cookie)与 `Secure`(仅限 HTTPS 加密传输)。
* 3. 【网络防火墙与反向代理适配 (Reverse Proxy Header)】:
* - 配置 {@link ForwardedHeaderFilter} 放在过滤器链最前端(`Integer.MIN_VALUE`),
* 精准获取经过 Nginx / ALB 代理后终端的真实客户端 IP(X-Forwarded-For);
* - 自定义 {@link StrictHttpFirewall}:放行 URL 编码斜杠(`%2F`)与百分号,
* 支持 Base64 加密的动态 Token 路由安全通过。
* 4. 【传输安全 (HSTS) 与内容安全策略 (CSP)】:
* - 启用 HSTS (HTTP Strict Transport Security) 预加载,强制客户端全站使用 HTTPS;
* - 密码加密方案:采用工业级单向散列加盐算法 {@link BCryptPasswordEncoder}。
*
* @author MiDM Core Platform Team
*/
@Configuration
public class SecurityConfig {
@Autowired
private BuildProperties buildProperties;
@Value("${spring.thymeleaf.cache: true}")
private boolean isDebug;
/**
* 配置 Servlet 上下文 Cookie 安全属性
*/
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
public void onStartup(ServletContext servletContext) throws ServletException {
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(SecurityConfig.this.isDebug);
sessionCookieConfig.setSecure(SecurityConfig.this.isDebug);
}
};
}
/**
* 【核心安全过滤链】配置认证、防护头与 CSP 策略
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
// 写入统一的服务端指纹安全响应头
StaticHeadersWriter headerWriter = new StaticHeadersWriter("Server", new String[]{"MiDM Host/MiTAC Digital", this.buildProperties.getVersion()});
// 针对 API 与 WebSocket 交互关闭 CSRF,禁用默认表单与 Basic 认证(由系统自定义 Token 过滤器接管)
httpSecurity.csrf((csrf) -> csrf.disable())
.httpBasic((httpBasic) -> httpBasic.disable())
.formLogin((formLogin) -> formLogin.disable());
// 配置内容安全策略 (CSP)
httpSecurity.headers((headers) -> headers.addHeaderWriter(headerWriter)
.contentSecurityPolicy("default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *;"));
// 强制启用 HSTS 传输安全保障
httpSecurity.headers((headers) -> headers.httpStrictTransportSecurity().preload(true).requestMatcher(AnyRequestMatcher.INSTANCE));
return (SecurityFilterChain)httpSecurity.build();
}
/**
* 反向代理转发头过滤器(保障真实 IP 提取)
*/
@Bean
public FilterRegistrationBean forwardedHeaderFilter() {
FilterRegistrationBean<ForwardedHeaderFilter> filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new ForwardedHeaderFilter());
filterRegistrationBean.setOrder(Integer.MIN_VALUE);
return filterRegistrationBean;
}
/**
* 自定义 HTTP 防火墙规约
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.httpFirewall(this.httpFirewall());
}
/**
* 放宽特殊字符以兼容 Base64 令牌与 RESTful 动态参数
*/
@Bean
public HttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowSemicolon(true);
firewall.setAllowUrlEncodedPeriod(true);
firewall.setAllowUrlEncodedPercent(true);
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
/**
* 全局密码散列加密器(BCrypt)
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,71 @@
package com.midm.app;
import com.midm.service.device.DeviceService;
import com.midm.service.file.ReportService;
import com.midm.service.news.NewsMessageService;
import com.midm.service.org.SiteService;
import com.midm.service.org.UserService;
import com.midm.service.system.HelpMessageService;
import com.midm.service.system.HostLicenseService;
import com.midm.service.system.LocaleService;
import com.midm.service.system.RestoreService;
import com.midm.service.system.SettingsService;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class StartupKeeper {
@Autowired
private HostLicenseService hostLicenseService;
@Autowired
private DeviceService deviceService;
@Autowired
private SettingsService settingsService;
@Autowired
private LocaleService localeService;
@Autowired
private UserService userService;
@Autowired
private HelpMessageService helpMessageService;
@Autowired
private NewsMessageService newsMessageService;
@Autowired
private ReportService reportService;
@Autowired
private SiteService siteService;
@Autowired
private RestoreService restoreService;
@EventListener({ContextRefreshedEvent.class})
private void contextRefreshedEvent() {
this.setDefaultTimeZone();
this.settingsService.loadSettings();
if (this.settingsService.syncOnStarts()) {
this.restoreService.restore((String)null);
}
this.hostLicenseService.validateLicense();
this.localeService.loadLocaleAndResources();
this.helpMessageService.loadMessages();
if (this.hostLicenseService.isPrimaryServer()) {
this.userService.updateUserNameIfNotExists();
this.userService.clearExpiredTokens();
this.reportService.expireReport();
this.deviceService.initDeviceStatus();
this.deviceService.clearOrphans();
this.siteService.clearOrphans();
this.newsMessageService.removeExpiredMessages();
this.newsMessageService.scheduleToNotify();
}
}
private void setDefaultTimeZone() {
TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC");
System.setProperty("user.timezone", defaultTimeZone.getID());
TimeZone.setDefault(defaultTimeZone);
}
}
@@ -0,0 +1,40 @@
package com.midm.app;
import com.midm.websocket.message.QueryHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* ======================================================================================
* WebSocket 全双工通信配置类
* ======================================================================================
*
* <p>【架构设计与业务场景】
* 1. 负责开启系统全双工实时通信能力({@link EnableWebSocket}),作为物联网终端与云端管理控制台的接入网关。
* 2. 路由映射:将 "/query" 端点绑定到核心消息处理器 {@link QueryHandler}。
* 3. 跨域策略:允许跨域请求(AllowedOrigins: "*"),支持 Web 前端管理后台和不同子网终端的安全接入。
*
* @author MiDM Core Platform Team
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
/** 核心 WebSocket 消息与连接生命周期处理器 */
@Autowired
private QueryHandler queryHandler;
/**
* 注册 WebSocket 处理器与通信端点
*
* @param registry WebSocket 处理器注册中心
*/
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册 "/query" 端点,用于处理终端注册(ENROLL)、遥测上报(REPORT)、心跳(PING/PONG)及实时控制指令下发
registry.addHandler(this.queryHandler, new String[]{"/query"}).setAllowedOrigins(new String[]{"*"});
}
}
@@ -0,0 +1,33 @@
package com.midm.app.converter;
import com.mitac.cell.utils.McDateTimeUtils;
import java.util.Date;
import org.joda.time.DateTime;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class DateConverter implements Converter {
public Date convert(String source) {
DateTime date = null;
try {
date = new DateTime(new Date(Long.parseLong(source)));
} catch (Exception var6) {
try {
date = DateTime.parse(source);
} catch (Exception var5) {
date = McDateTimeUtils.parseDate(source, (String)null);
if (date == null) {
date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z 'GMT'");
}
if (date == null) {
date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z z");
}
}
}
return date == null ? null : date.toDate();
}
}
@@ -0,0 +1,13 @@
package com.midm.app.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
@Component
public class DirectionConverter implements Converter {
public Sort.Direction convert(String source) {
return Direction.valueOf(source.toUpperCase());
}
}
@@ -0,0 +1,20 @@
package com.midm.app.converter;
import com.google.gson.JsonElement;
import com.mitac.cell.utils.McJsonUtils;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class JsonElementConverter implements Converter {
public JsonElement convert(String source) {
try {
source = URLDecoder.decode(source, Charset.defaultCharset());
return McJsonUtils.toJsonElement(source);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,20 @@
package com.midm.app.converter;
import com.google.gson.JsonObject;
import com.mitac.cell.utils.McJsonUtils;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class JsonObjectConverter implements Converter {
public JsonObject convert(String source) {
try {
source = URLDecoder.decode(source, Charset.defaultCharset());
return McJsonUtils.toJsonElement(source).getAsJsonObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,12 @@
package com.midm.app.converter;
import com.mitac.cell.internet.http.UserAgent;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class UserAgentConverter implements Converter {
public UserAgent convert(String source) {
return new UserAgent(source);
}
}
@@ -0,0 +1,46 @@
package com.midm.constant;
public class GeneralConst {
public static final String KEY_KEY = "key";
public static final String KEY_VALUE = "value";
public static final String KEY_AUTH_KEY = "auth_key";
public static final String KEY_ID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_TITLE = "title";
public static final String KEY_PHONE = "phone";
public static final String KEY_MOBILE = "mobile";
public static final String KEY_THEME = "theme";
public static final String KEY_CONTENT = "content";
public static final String KEY_SUMMARY = "summary";
public static final String KEY_USER = "user";
public static final String KEY_OWNER = "owner";
public static final String DEFAULT = "default";
public static final String HTML = ".html";
public static final String CATEGORY_APP = "app";
public static final String CATEGORY_GENERAL = "general";
public static final String CATEGORY_OTA = "ota";
public static final String CATEGORY_WEBAPP = "webapp";
public static final String CATEGORY_OTHER = "other";
public static final String CATEGORY_REPORT = "report";
public static final String CATEGORY_FILE = "file";
public static final String CATEGORY_DEVICE = "device";
public static final String CATEGORY_SCREEN = "screen";
public static final String CATEGORY_INSTALLED = "installed";
public static final String CATEGORY_STORAGE = "storage";
public static final String PROFILE = "profile";
public static final String LOGO_LIGHT = "light";
public static final String LOGO_DARK = "dark";
public static final String FAVICON = "favicon";
public static final String PROFILE_USERGROUP = "usergroup";
public static final String PROFILE_ORGANIZATION = "org";
public static final String PROFILE_SITE = "site";
public static final String PROFILE_DEVICE_GROUP = "deviceGroup";
public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L;
public static final String KEY_LANGUAGE = "language";
public static final String KEY_DESC = "desc";
public static final String KEY_DEVICE = "device";
public static final String KEY_GROUP = "group";
public static final String KEY_GROUPS = "groups";
public static final String KEY_GROUP_UUID = "groupUuid";
public static final String KEY_APP_FILE = "appFile";
}
@@ -0,0 +1,15 @@
package com.midm.constant;
import java.util.Locale;
import org.springframework.data.mongodb.core.query.Collation;
public class LocaleConst {
public static final Locale DEFAULT_LOCALE;
public static final String EN_US = "en-US";
public static final Collation COLLATION_DEFAULT;
static {
DEFAULT_LOCALE = Locale.US;
COLLATION_DEFAULT = Collation.of(DEFAULT_LOCALE).strength(2);
}
}
@@ -0,0 +1,8 @@
package com.midm.constant;
public class LocationConst {
public static String KEY_LAT = "lat";
public static String KEY_LATITUDE = "latitude";
public static String KEY_LON = "lon";
public static String KEY_LONGITUDE = "longitude";
}
@@ -0,0 +1,191 @@
package com.midm.constant;
public class MidmConst {
public static final String MIDM = "midm";
public static final String KEY_REQUEST = "request";
public static final String KEY_PARAMS = "params";
public static final String KEY_ID = "_id";
public static final String KEY_UUID = "uuid";
public static final String KEY_EULA = "eula";
public static final String KEY_SITE = "site";
public static final String KEY_SITES = "sites";
public static final String KEY_SITE_UUID = "siteUuid";
public static final String KEY_SITE_HAS_BATTERY_PLAN = "hasBatteryPlan";
public static final String KEY_GROUP_UUID = "groupUuid";
public static final String KEY_PARENT_UUID = "parentUuid";
public static final String KEY_ID_NAME = "idName";
public static final String KEY_SITE_ID_NAME = "siteIdName";
public static final String KEY_USER_UUID = "userUuid";
public static final String KEY_DEVICE_UUID = "deviceUuid";
public static final String KEY_DEVICE_SERIAL = "deviceSerial";
public static final String KEY_DEVICE_PROFILE = "deviceProfile";
public static final String KEY_RSA = "rsa";
public static final String KEY_SERIALNO = "serialNo";
public static final String KEY_TIMEZONE = "timeZone";
public static final String KEY_WIFI_MAC = "wifiMac";
public static final String KEY_FROM = "from";
public static final String KEY_TO = "to";
public static final String KEY_SELF_ENROLL = "selfEnroll";
public static final String KEY_IF_EXISTS = "ifExists";
public static final String KEY_RTC_ENABLED = "rtcEnabled";
public static final String KEY_SOURCES = "sources";
public static final String KEY_EMAIL = "email";
public static final String KEY_ENABLE = "enable";
public static final String KEY_ENABLED = "enabled";
public static final String KEY_CLIENT_VERSION = "clientVersion";
public static final String KEY_BATTERY_SERIAL = "batterySerial";
public static final String KEY_BATTERY_CONDITION = "batteryCondition";
public static final String KEY_COMMAND = "command";
public static final String KEY_CATEGORY = "category";
public static final String KEY_LOG = "log";
public static final String KEY_LOGGED_AT = "loggedAt";
public static final String KEY_INCLUDES = "includes";
public static final String KEY_URL = "url";
public static final String KEY_PATH = "path";
public static final String KEY_ROOT = "root";
public static final String KEY_OWNER = "owner";
public static final String KEY_REGION = "region";
public static final String KEY_MODEM = "modem";
public static final String KEY_USER = "user";
public static final String KEY_DEST = "dest";
public static final String KEY_PUSH = "push";
public static final String KEY_MOVE = "move";
public static final String KEY_DELETE = "delete";
public static final String KEY_EXTRACT = "extract";
public static final String KEY_KEEP_IN_HOST = "keepInHost";
public static final String KEY_IS_GLOBAL = "isGlobal";
public static final String KEY_UPDATE_VIA = "update_via";
public static final String KEY_SILENT_UPDATE = "silent_update";
public static final String KEY_ALLOW_DOWNGRADE = "allow_downgrade";
public static final String KEY_SHOW_PROGRESS = "show_progress";
public static final String KEY_FORCE_TO_UPDATE = "force_to_update";
public static final String KEY_REMOVE_AFTER_INSTALL = "remove_after_install";
public static final String KEY_CREATED = "created";
public static final String KEY_UPDATED = "updated";
public static final String KEY_APPLIED = "applied";
public static final String KEY_REPORTED_AT = "reportedAt";
public static final String KEY_RESELLER = "reseller";
public static final String KEY_RESELLER_SITE = "resellerSite";
public static final String KEY_IS_RESELLER = "isReseller";
public static final String KEY_DEVICE_LIMIT = "deviceLimit";
public static final String KEY_LICENSE = "license";
public static final String KEY_RENEW = "renew";
public static final String KEY_AUTO_RENEW = "autoRenew";
public static final String KEY_RENEW_TO_SAME_MODEL = "renewToSameModel";
public static final String KEY_MODEL = "model";
public static final String KEY_LICENSE_MODEL = "licenseModel";
public static final String KEY_LICENSE_FEATURE = "licenseFeature";
public static final String KEY_FEATURES = "features";
public static final String KEY_PLAN = "plan";
public static final String KEY_TARGET_PLAN = "targetPlan";
public static final String KEY_SYSTEM = "system";
public static final String KEY_STORE = "store";
public static final String KEY_KEYSTORE = "keyStore";
public static final String KEY_REPORT = "report";
public static final String KEY_TEMP = "temp";
public static final String KEY_DATE_TIME = "dateTime";
public static final String KEY_HOUR_FORMAT = "hourFormat";
public static final String KEY_ACTIVITY = "activity";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_TOTAL = "total";
public static final String KEY_FRESH = "fresh";
public static final String KEY_FRESH_EXPIRING = "freshExpiring";
public static final String KEY_USED = "used";
public static final String KEY_USED_EXPIRING = "usedExpiring";
public static final String KEY_ACTIVE = "active";
public static final String KEY_INACTIVE = "inactive";
public static final String KEY_EXPIRED = "expired";
public static final String KEY_LICENSED = "licensed";
public static final String KEY_MEMORY = "memory";
public static final String KEY_BATTERY = "battery";
public static final String KEY_LOCATION = "location";
public static final String KEY_DATA_USAGE = "dataUsage";
public static final String REQUEST_APPS = "apps";
public static final String REQUEST_OTAS = "otas";
public static final String REQUEST_FILES = "files";
public static final String REQUEST_ENROLL = "enroll";
public static final String REQUEST_DATA_USAGE = "data_usage";
public static final String KEY_REPEAT_OPTION = "repeatOption";
public static final String KEY_REPEAT_PERIOD = "repeatPeriod";
public static final String KEY_REPEAT_EVERY = "repeatEvery";
public static final String VALUE_HOST = "host";
public static final String VALUE_DEVICE = "device";
public static final String VALUE_WIFI = "wifi";
public static final String VALUE_MOBILE = "mobile";
public static final String VALUE_BOTH = "both";
public static final String VALUE_ALL = "all";
public static final String VALUE_SELECTED = "selected";
public static final String TYPE_WIFI = "WIFI";
public static final String TYPE_MOBILE = "MOBILE";
public static final String VALUE_LOGO = "logo";
public static final String VALUE_PROFILE = "profile";
public static final String VALUE_BACKGROUND = "background";
public static final int VALUE_DEFAULT_HEART_BEAT = 300;
public static final String KEY_WEBSOCKET_EXTENSION = "sec-websocket-extensions";
public static final String REQUEST_UPDATE_PROFILE = "update_profile";
public static final int CODE_UPDATE_PROFILE = 131;
public static final String REQUEST_UPDATE_ALL_PROFILES = "update_profile_all";
public static final int CODE_UPDATE_ALL_PROFILES = 132;
public static final String REQUEST_SYNC_PROFILE = "sync_profile";
public static final int CODE_SYNC_PROFILE = 136;
public static final String REQUEST_REMOVE_PROFILE = "remove_profile";
public static final int CODE_REMOVE_PROFILE = 136;
public static final String KEY_THEME = "theme";
public static final String KEY_NOTIFICATION = "noti";
public static final String KEY_COUNT = "count";
public static final String KEY_PAGE = "page";
public static final String KEY_EXPIRY = "expiry";
public static final String KEY_LICENSE_EXPIRY = "licenseExpiry";
public static final String KEY_FINAL_EXPIRY = "finalExpiry";
public static final String KEY_ACTIVATED_AT = "activatedAt";
public static final String KEY_ACTIVATION_COUNT = "activationCount";
public static final String KEY_CHILD_SITE = "childSite";
public static final String KEY_URL_EXPIRY = "urlExpiry";
public static final String KEY_ICON_EXPIRY = "iconExpiry";
public static final String KEY_EXPIRED_IN_10 = "expiredIn10";
public static final String KEY_EXPIRED_IN_30 = "expiredIn30";
public static final String KEY_EXPIRED_IN_45 = "expiredIn45";
public static final String KEY_EXPIRED_IN_45_WITH_AUTO_RENEW = "expiredIn45WithAutoRenew";
public static final String KEY_FOR_WHAT = "forWhat";
public static final String KEY_REFERENCE = "reference";
public static final String KEY_LOGGER = "logger";
public static final String KEY_INSTALL = "install";
public static final String KEY_INSTALL_APPS = "installApps";
public static final String KEY_SHOW = "show";
public static final String KEY_MSETTINGS = "msettings";
public static final String KEY_WALLPAPER = "wallpaper";
public static final String PLAN_STANDARD_BATTERYPRO = "standardWithBatteryPro";
public static final String PLAN_STANDARD = "standard";
public static final String PLAN_LITE = "lite";
public static final String KEY_ERROR = "error";
public static final String KEY_PAGE_FOR = "pageFor";
public static final String KEY_HAS_USER = "hasUser";
public static final String KEY_IP = "ip";
public static final String KEY_IP_ADDR = "ip_addr";
public static final String KEY_PUBLIC_IP = "public_ip";
public static final String KEY_ADD = "add";
public static final String KEY_REMOVE = "remove";
public static final String KEY_PO = "po";
public static final String KEY_NOTE = "note";
public static final String KEY_NOTES = "notes";
public static final String KEY_SETTINGS = "settings";
public static final String KEY_PROFILES = "profiles";
public static final String KEY_STATUS = "status";
public static final String STATUS_ADDED = "added";
public static final String STATUS_REPLACED = "replaced";
public static final String STATUS_REMOVED = "removed";
public static final String VALUE_UNKNOWN = "unknown";
public static final String VALUE_NONE = "none";
public static final String VALUE_NEVER = "never";
public static final String VALUE_DISABLED = "disabled";
public static final String VALUE_ONCE = "once";
public static final String VALUE_BLOCKED = "blocked";
public static final String VALUE_MITAC = "mitac";
public static final String PACKAGE_MIDM_CLIENT = "com.mitac.midm.client";
public static final String PACKAGE_MIDM_SYSTEM = "com.mitac.midm.system";
public static final String PACKAGE_MILOCK = "com.mitac.milock";
public static final String PACKAGE_MIBATTERY = "com.mitac.utils.battery";
public static final String COLLECTION_MIDM_LOG = "midmLog";
public static final String COLLECTION_DEVICE_REPORT = "deviceReport";
public static final String COLOR_RED = "red";
}
@@ -0,0 +1,93 @@
package com.midm.constant;
public class PropertyConst {
public static final String CATEGORY_HADRWARE = "hardware_info";
public static final String CATEGORY_SOFTWARE_INFO = "software_info";
public static final String CATEGORY_NETWORK = "network";
public static final String CATEGORY_SHIPMENT = "shipment";
public static final String CATEGORY_EVENT = "event";
public static final String CATEGORY_ACTIVITY = "activity";
public static final String CATEGORY_UPDATE = "update";
public static final String ROLE = "role";
public static final String ADMIN = "admin";
public static final String ADMINISTRATOR = "Administrator";
public static final String NAME = "name";
public static final String NATIONAL_ID = "nationalId";
public static final String GENDER = "gender";
public static final String COMMENT = "comment";
public static final String MEMO = "memo";
public static final String EMAIL = "email";
public static final String LOGIN_ID = "loginId";
public static final String PASSWORD = "password";
public static final String PROPERTIES = "properties";
public static final String USER_PROPERTIES = "userProperties";
public static final String REGISTER_PROPERTIES = "registerProperties";
public static final String KEEP_SIGNIN = "keepSignIn";
public static final String LAST_SITE = "lastSite";
public static final String LAST_PAGE = "lastPage";
public static final String DEPARTMENT = "dept";
public static final String PLACE = "place";
public static final String REFERENCE = "reference";
public static final String POST_FROM = "postFrom";
public static final String POST_TO = "postTo";
public static final String DOCUMENT_NO = "doc_no";
public static final String UPDATE = "update";
public static final String SERIAL_NO = "serial_no";
public static final String PART_NO = "part_no";
public static final String PALLET_NO = "pallet_mo";
public static final String CARTON_SN = "carton_no";
public static final String ACTIVE = "active";
public static final String WIFI = "wifi";
public static final String WIFI_MAC = "wifi_mac";
public static final String MAC_ADDRESS = "mac_address";
public static final String SKU_ID = "sku_id";
public static final String COMPATIBLE_SKUS = "compatibleSkus";
public static final String DEVICE_ID = "deviceId";
public static final String SSID = "ssid";
public static final String TELEPHONY = "telephony";
public static final String PRODUCT_ID = "product_id";
public static final String PRODUCT_MODEL = "product_model";
public static final String BUILD_NO = "build_no";
public static final String DISPLAY_ID = "display_id";
public static final String PRODUCT_DISPLAY_ID = "product_display_id";
public static final String PRE_DISPLAY_ID = "preDisplayId";
public static final String BUILD_DATE = "build_date";
public static final String REGION_VERSION = "region_version";
public static final String REGION_BUILD_DATE = "region_build_date";
public static final String CUSTOMER_ID = "customer_id";
public static final String ACTIVE_NETWORK = "active_network";
public static final String SDK_VERSION = "sdk_version";
public static final String SCRIPT_VERSION = "script_version";
public static final String RELEASE_VERSION = "release_version";
public static final String OS_VERSION = "os_version";
public static final String GMS_AVAILABLE = "gms_available";
public static final String TYPE = "type";
public static final String PRE_BUILD = "preBuild";
public static final String POST_BUILD = "postBuild";
public static final String STATE = "state";
public static final String IS_ONLINE = "isOnline";
public static final String STATE_REGISTERED = "registered";
public static final String STATE_ENROLLED = "enrolled";
public static final String STATE_RETIRED = "retired";
public static final String FILE_URL = "fileUrl";
public static final String ICON_URL = "iconUrl";
public static final String SETTINGS_HEARTBEAT_INTERVAL = "websocket.heartbeat.interval";
public static final String MESSAGE = "message";
public static final String FILE_NAME = "fileName";
public static final String FILE_LENGTH = "fileLength";
public static final String PACKAGE = "package";
public static final String PACKAGE_NAME = "packageName";
public static final String LABEL = "label";
public static final String VERSION_CODE = "versionCode";
public static final String VERSION_NAME = "versionName";
public static final String CHECKSUM = "checksum";
public static final String CERT_MD5 = "certMd5";
public static final String STORAGES = "storages";
public static final String MEMORY = "memory";
public static final String BATTERY = "battery";
public static final String TEMPERATURE = "temperature";
public static final String VOLTAGE = "voltage";
public static final String CHARGE_LEVEL = "level";
public static final String CHARGING_STATUS = "charginStatus";
public static final String PLUGGED = "plugged";
}
@@ -0,0 +1,82 @@
package com.midm.controller;
import com.google.common.base.Strings;
import com.midm.model.org.User;
import com.midm.security.UserPrincipal;
import com.midm.service.org.SiteService;
import com.midm.service.org.UserService;
import com.midm.service.system.LocaleService;
import com.mitac.cell.utils.McStringUtils;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.servlet.LocaleResolver;
public class BaseController {
@Autowired
protected LocaleResolver localeResolver;
@Autowired
protected LocaleService localeService;
@Autowired
protected UserService userService;
@Autowired
protected SiteService siteService;
protected User user = null;
protected String theme = "default";
protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.init(request, response, authentication, (String)null);
}
protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication, String localeTag) {
this.determineUser(request, authentication);
String userLocale = !Strings.isNullOrEmpty(localeTag) ? localeTag : (this.user != null ? this.user.getSettingAsString("language") : request.getLocale().toLanguageTag());
if (McStringUtils.isNullOrEmpty(userLocale)) {
userLocale = request.getLocale().toLanguageTag();
}
Locale altLocale = this.localeService.findAltLocale(userLocale);
if (this.user != null) {
String altLocaleTag = altLocale.toLanguageTag();
if (userLocale == null || !this.user.isSameLocale(altLocaleTag)) {
this.userService.changeLocale(this.user, altLocaleTag);
}
}
this.localeResolver.setLocale(request, response, altLocale);
}
protected String getView(Authentication authentication, String viewName) {
return this.getResource(authentication, viewName + ".html");
}
protected String getResource(Authentication authentication, String fileName) {
User user = UserPrincipal.getUser(authentication);
String theme = user == null ? "default" : user.getTheme();
return theme + fileName;
}
protected String getTemplateResource(Authentication authentication, String fileName) {
if (this.user == null) {
this.user = UserPrincipal.getUser(authentication);
}
String theme = this.user == null ? "default" : this.user.getTheme();
return "templates/" + theme + fileName;
}
private void determineUser(HttpServletRequest request, Authentication authentication) {
if (authentication != null) {
synchronized(authentication) {
this.user = UserPrincipal.getUser(authentication);
this.theme = this.user != null ? this.user.getTheme() : "default";
}
} else {
this.user = null;
this.theme = "default";
}
}
}
@@ -0,0 +1,236 @@
package com.midm.controller;
import com.midm.model.device.Device;
import com.midm.model.org.Site;
import com.midm.model.org.User;
import com.midm.model.org.UserRole;
import com.midm.model.org.UserToken;
import com.midm.service.device.DeviceService;
import com.midm.service.message.WebSocketSessionManager;
import com.mitac.cell.internet.http.McRequest;
import com.mitac.cell.utils.McUuidUtils;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;
/**
* ======================================================================================
* 移动终端设备远程接入与控制路由控制器 (DeviceController)
* ======================================================================================
*
* <p>【架构设计与安全亮点】
* 1. 业务场景:
* - 管理员在监控大屏或告警邮件中点击设备远程查看链接,一键无感知跳转至设备的远程桌面或管理详情;
* - 设备维护人员使用移动端或外链进行快速应急远程排障(Remote Assist)。
* 2. 【安全机制一:一次性动态安全令牌 (OTT - One-Time Token)】:
* - 在 `GET /device/{accessToken}` 中,Token 经 Base64 编码,且类型标记为 'D'(Device Token);
* - 验证通过后**立即从数据库中物理删除**({@link #remoteView} 第 56 行),从根源杜绝重放攻击(Replay Attack);
* - 严格校验 Token 是否过期(isExpired)以及租户数据隔离边界。
* 3. 【安全机制二:多租户 RBAC 权限与版本授权控制】:
* - 严格校验操作人是否归属于设备所在租户(Site);
* - 校验用户角色是否拥有 `DEVICE_MANAGE_ROLES` 权限;
* - 针对租户订阅版本(如基础版 Lite vs 企业版 Pro),对高级功能标签页(如 WebRTC 远程控制 remoteControl、GPS实时轨迹 location)进行动态降级限制。
*
* @author MiDM Core Platform Team
*/
@Controller
public class DeviceController extends BaseController {
/** 设备详情页支持的功能标签页集合 */
private static List tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs");
@Autowired
private DeviceService deviceService;
@Autowired
private WebSocketSessionManager sessionManager;
/**
* 【安全快捷通道】基于一次性动态 Token 的设备远程控制接入接口
*
* @param request HTTP 请求
* @param response HTTP 响应
* @param authentication 当前 Spring Security 认证上下文
* @param model 视图模型
* @param accessToken Base64 编码的一次性设备访问令牌
* @param language 国际化语言(默认 "en-US")
* @param tab 目标定位标签页(如 "remoteControl" 远程桌面、"location" GPS轨迹,默认 "general")
* @return 重定向到单页面应用前端详情路由的 RedirectView
* @throws IOException 网络 IO 异常
*/
@RequestMapping(
value = {"/device/{accessToken}"},
method = {RequestMethod.GET}
)
public RedirectView remoteView(HttpServletRequest request, HttpServletResponse response,
Authentication authentication, Model model,
@PathVariable String accessToken,
@RequestParam(required = false, defaultValue = "en-US") String language,
@RequestParam(required = false, defaultValue = "general") String tab) throws IOException {
// 1. 获取当前会话登录的用户身份
User loggedUser = this.userService.authorizedUser(authentication, (String)null);
if (authentication != null) {
UserToken prevToken = (UserToken)authentication.getCredentials();
if (!this.userService.existsById(UserToken.class, prevToken)) {
this.logout(loggedUser);
}
}
// 2. 解码并反序列化 Token UUID
accessToken = URLDecoder.decode(accessToken, Charset.defaultCharset());
UUID tokenUuid = McUuidUtils.toUuidFromBase64(accessToken);
UserToken deviceToken = this.userService.findToken(tokenUuid);
// 3. 安全性严格校验:必须存在且类型为 'D' (Device Token),且未过期
if (deviceToken != null && deviceToken.getTokenType() == 'D' && !deviceToken.isExpired()) {
// 【核心安全点:一次性销毁防重放】
this.userService.delete(deviceToken);
UUID requesterUuid = deviceToken.getUserUuid();
// 若当前登录人与发券人不一致,先清除旧会话
if (loggedUser != null && !loggedUser.getUuid().equals(requesterUuid)) {
this.logout(loggedUser);
loggedUser = null;
}
// 自动为请求发起者建立登录认证态
if (loggedUser == null) {
loggedUser = this.userService.findUserByUserUuid(requesterUuid);
authentication = this.userService.authorizeLogin(loggedUser);
}
loggedUser.setProfile("forRemote", true);
this.init(request, response, authentication, language);
// 4. 定位目标设备(优先在线实例)并校验租户归属隔离
UUID deviceUuid = deviceToken.getDeviceUuid();
Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid);
if (device != null && this.user.isBelongedToSite(device.getSiteUuid())) {
if (!tabs.contains(tab)) {
tab = "general";
}
// 5. 商业版本功能门限鉴权:若租户为 Lite 简版且未购买该功能,强制降级到概要标签
Site site = this.siteService.findByUuid(device.getSiteUuid());
if (!tab.equals("general") && site.isLite() && !site.isFeatureAllowed("device", tab)) {
tab = "general";
}
// 跳转前端对应功能视图
return this.remoteView(request, device, tab);
} else {
this.logout(loggedUser);
response.sendError(401);
return null;
}
} else {
response.sendError(400, "The remote control URL is unavailable.");
if (authentication != null) {
this.logout(loggedUser);
}
return null;
}
}
/**
* 【凭证直连通道】基于企业邮箱、密码/凭证和设备序列号直接接入远程管理
*/
@RequestMapping(
value = {"/device/{email}/{credential}/{serialNo}"},
method = {RequestMethod.GET}
)
public RedirectView remoteView(HttpServletRequest request, HttpServletResponse response,
Authentication authentication, Model model,
@PathVariable String email,
@PathVariable String credential,
@PathVariable String serialNo,
@RequestParam(required = false, defaultValue = "en-US") String language,
@RequestParam(required = false, defaultValue = "general") String tab) throws IOException {
// 1. 查找目标硬件设备
Device device = this.deviceService.findBySerialNo(serialNo);
if (device == null) {
this.logout(this.user);
response.sendError(401, "The device may not exist.");
return null;
} else {
Site site = this.siteService.findByUuid(device.getSiteUuid());
User user = this.userService.authorizedUser(authentication, (String)null);
if (user != null && !user.getEmail().equals(email)) {
this.logout(user);
user = null;
}
// 2. 校验用户身份合法性
if (user == null) {
user = this.userService.findUserByEmail(site.getUuid(), email);
if (user == null || !user.getEnabled() || !user.isBelongedToSite(site)) {
response.sendError(401, "The account may not exist or disabled or not belonged to the site.");
return null;
}
}
authentication = this.userService.updateAuthorizedUser(user);
// 3. 校验设备管理角色权限
if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) {
this.logout(user);
response.sendError(401, "The user doesn't have the role to manage the device.");
return null;
} else if (site != null && (site.isCredentialMatched(credential) || this.userService.matchPassword(user, credential))) {
// 4. 凭证比对成功
if (!tabs.contains(tab)) {
tab = "general";
}
if (!tab.equals("general") && site.isLite() && !site.isFeatureAllowed("device", tab)) {
tab = "general";
}
user.setProfile("forRemote", true);
this.init(request, response, authentication, language);
return this.remoteView(request, device, tab);
} else {
response.sendError(401, "The site credential or password is mismatched.");
return null;
}
}
}
/**
* 安全退出并彻底销毁会话与 SecurityContext
*/
private void logout(User loggedUser) {
if (loggedUser != null) {
this.sessionManager.logout(loggedUser);
SecurityContextHolder.getContext().setAuthentication((Authentication)null);
this.userService.deleteLoginToken(loggedUser);
}
}
/**
* 构建单页面应用前端重定向路由地址
*/
private RedirectView remoteView(HttpServletRequest request, Device device, String tab) {
String url = McRequest.getBaseUrl(request, String.format("#/device/details/%s/%s/%s", device.getUuid(), device.getSerialNo(), tab));
url = URLDecoder.decode(url, Charset.defaultCharset());
RedirectView view = new RedirectView(url);
return view;
}
}
@@ -0,0 +1,123 @@
package com.midm.controller;
import com.google.common.base.Strings;
import com.mitac.cell.utils.McStringUtils;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ExceptionController extends BaseController implements ErrorController {
@RequestMapping(
value = {"error"},
method = {RequestMethod.GET}
)
public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "JSESSIONID",defaultValue = "") String sessionId, Model model, @RequestParam(required = false) String language) {
int errorCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
if (!Strings.isNullOrEmpty(sessionId)) {
this.init(request, (HttpServletResponse)null, authentication, language);
String contextPath = (String)request.getAttribute("javax.servlet.forward.context_path");
String path = (String)request.getAttribute("javax.servlet.error.request_uri");
if (errorCode == 404) {
if (authentication == null) {
return "redirect:/";
} else {
String route = path.substring(contextPath.length());
return "forward:/#" + route;
}
} else {
Error error = new Error(errorCode);
String message = (String)request.getAttribute("javax.servlet.error.message");
if (!Strings.isNullOrEmpty(message)) {
error.setMessage(message);
}
Exception ex = (Exception)request.getAttribute("javax.servlet.error.exception");
if (ex != null) {
error.setException(ex);
}
model.addAttribute("path", path);
model.addAttribute("error", error);
String stackTrace = McStringUtils.stackTrace(ex);
model.addAttribute("stackTrace", stackTrace);
return this.getView(authentication, "/error");
}
} else {
try {
response.sendError(errorCode);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
@RequestMapping({"generate_204", "gen_204"})
public void gen204(HttpServletRequest request, HttpServletResponse response) {
try {
response.sendError(204);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(
value = {"blocked"},
method = {RequestMethod.GET}
)
public String blocked(HttpServletRequest request, Authentication authentication, Model model, @RequestParam(required = false) String url, @RequestParam(required = false) String serialNo, @RequestParam(required = false) String language) {
this.init(request, (HttpServletResponse)null, authentication, language);
model.addAttribute("url", URLDecoder.decode(url, Charset.defaultCharset()));
model.addAttribute("serialNo", serialNo);
Error error = new Error(408);
model.addAttribute("error", error);
return this.getView(authentication, "/error");
}
private class Error {
private int code;
private Exception exception;
private String message;
public Error(int code) {
this.setCode(code);
}
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
public Exception getException() {
return this.exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
@@ -0,0 +1,79 @@
package com.midm.controller;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class FragmentController extends BaseController {
@RequestMapping(
value = {"/view/**"},
method = {RequestMethod.GET}
)
public String view(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model) {
this.init(request, response, authentication);
model.addAttribute("theme", this.theme);
if (authentication == null) {
model.addAttribute("hasUser", this.userService.hasUser());
}
return this.getView(authentication, request.getServletPath());
}
@RequestMapping(
value = {"/view/system/resource"},
method = {RequestMethod.GET}
)
public String resourceView(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @RequestParam String category) {
super.init(request, response, authentication);
model.addAttribute("category", category);
return "template/system/resource.html";
}
@RequestMapping(
value = {"/fragment/{fragmentName}"},
method = {RequestMethod.GET}
)
public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName) {
super.init(request, response, authentication);
model.addAttribute("theme", this.theme);
if (authentication == null) {
model.addAttribute("hasUser", this.userService.hasUser());
}
String var10000 = this.getView(authentication, request.getServletPath());
return var10000 + " :: fragment";
}
@RequestMapping(
value = {"/fragment/{fragmentName}/{blockName}"},
method = {RequestMethod.GET}
)
public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName, @PathVariable String blockName) {
super.init(request, response, authentication);
String var10000 = this.getView(authentication, "/fragment/" + fragmentName);
return var10000 + " :: " + blockName;
}
@RequestMapping(
value = {"/dialog/{dialogName}"},
method = {RequestMethod.GET}
)
public String dialog(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String dialogName, @RequestParam(required = false) String category) {
this.init(request, response, authentication);
model.addAttribute("theme", this.theme);
if (authentication == null) {
model.addAttribute("hasUser", this.userService.hasUser());
}
String var10000 = this.getView(authentication, request.getServletPath());
return var10000 + " :: dialog";
}
}
@@ -0,0 +1,273 @@
package com.midm.controller;
import com.google.common.base.Strings;
import com.midm.model.org.Site;
import com.midm.model.org.UserToken;
import com.midm.security.UserPrincipal;
import com.mitac.cell.internet.http.McResponse;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;
@Controller
public class HomeController extends BaseController {
@RequestMapping(
value = {"/", "/index.html"},
method = {RequestMethod.GET}
)
public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, @CookieValue(value = "site.uuid",defaultValue = "") UUID siteUuid, @CookieValue(value = "locale",defaultValue = "en-US") String locale, Model model, @RequestHeader("host") String hostName, @RequestParam(required = false) String language, @RequestParam(required = false) String siteId) {
if (Strings.isNullOrEmpty(language)) {
language = locale;
}
if (authentication != null) {
UserToken token = (UserToken)authentication.getCredentials();
UserToken existingToken = token == null ? null : this.userService.findToken(token.getTokenUuid());
if (existingToken == null) {
SecurityContextHolder.getContext().setAuthentication((Authentication)null);
authentication = null;
if (token != null && token.getTokenUuid().equals(tokenUuid)) {
tokenUuid = null;
McResponse.setCookie(response, "user.token", (String)null);
}
}
}
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
if (authentication == null && tokenUuid != null) {
UserToken token = this.userService.findToken(tokenUuid);
if (token != null) {
authentication = this.userService.authorizeLogin(tokenUuid);
} else {
McResponse.setCookie(response, "user.token", (String)null);
}
}
if (authentication == null) {
if (!Strings.isNullOrEmpty(siteId)) {
Site site = siteId.equals("default") ? null : this.siteService.findByIdName(siteId);
if (site != null) {
siteUuid = site.getUuid();
model.addAttribute("siteUuid", siteUuid);
McResponse.setCookie(response, "site.uuid", siteUuid.toString());
} else {
siteUuid = null;
}
}
if (siteUuid != null) {
model.addAttribute("siteUuid", siteUuid);
}
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "login");
model.addAttribute("locale", language);
if (locale != null && language != null && !locale.equals(language)) {
McResponse.setCookie(response, "locale", language);
}
return this.getView(authentication, "/login");
} else {
this.user = UserPrincipal.getUser(authentication);
if (this.user == null) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "login");
model.addAttribute("locale", language);
if (locale != null && language != null && !locale.equals(language)) {
McResponse.setCookie(response, "locale", language);
}
return this.getView(authentication, "/login");
} else {
return this.getView(authentication, "/index");
}
}
}
@RequestMapping(
value = {"/remoteLogout"},
method = {RequestMethod.GET}
)
public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model, @RequestParam(required = false) String language) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
return this.getView(authentication, "/remoteLogout");
}
@RequestMapping(
value = {"/"},
method = {RequestMethod.POST}
)
public void homePost(HttpServletRequest request, HttpServletResponse response) {
try {
response.sendError(400);
} catch (IOException var4) {
}
}
@RequestMapping(
value = {"register"},
method = {RequestMethod.GET}
)
public String registerToModelSite(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, @RequestParam String modelSite, ModelMap model, @RequestParam(required = false) String language) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
UserToken token = null;
if (authentication == null && tokenUuid != null) {
token = this.userService.findToken(tokenUuid);
authentication = this.userService.authorizeLogin(tokenUuid);
}
if (authentication == null && token == null) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "register");
return this.getView(authentication, "/login");
} else {
return "forward:/";
}
}
@RequestMapping(
value = {"{modelSite}/register"},
method = {RequestMethod.GET}
)
public RedirectView redirectToRegister(ModelMap model, @PathVariable String modelSite, @RequestParam(required = false) String language) {
model.clear();
return new RedirectView("../register?modelSite=" + modelSite);
}
@RequestMapping(
value = {"/bypass", "/dpc"},
method = {RequestMethod.GET}
)
public String bypassMode(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
UserToken token = null;
if (authentication == null && tokenUuid != null) {
token = this.userService.findToken(tokenUuid);
authentication = this.userService.authorizeLogin(tokenUuid);
}
if (authentication == null && token == null) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "dpc");
return this.getView(authentication, "/login");
} else {
this.user = UserPrincipal.getUser(authentication);
if (this.user.getSettingAsBoolean("keepSignIn")) {
if (token == null && authentication != null) {
token = (UserToken)authentication.getCredentials();
}
if (token != null) {
Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString());
response.addCookie(cookie);
}
} else {
Cookie cookie = new Cookie("user.token", (String)null);
response.addCookie(cookie);
}
return this.getView(authentication, "/index");
}
}
@RequestMapping(
value = {"{modelSite}/bypass", "{modelSite}/dpc"},
method = {RequestMethod.GET}
)
public String bypassModeWithModel(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
UserToken token = null;
if (authentication == null && tokenUuid != null) {
token = this.userService.findToken(tokenUuid);
authentication = this.userService.authorizeLogin(tokenUuid);
}
if (authentication == null && token == null) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "dpc");
return this.getView(authentication, "/login");
} else {
this.user = UserPrincipal.getUser(authentication);
if (this.user.getSettingAsBoolean("keepSignIn")) {
if (token == null && authentication != null) {
token = (UserToken)authentication.getCredentials();
}
if (token != null) {
Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString());
response.addCookie(cookie);
}
} else {
Cookie cookie = new Cookie("user.token", (String)null);
response.addCookie(cookie);
}
return this.getView(authentication, "/index");
}
}
@RequestMapping(
value = {"/requestTrial"},
method = {RequestMethod.GET}
)
public String requestTrial(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
UserToken token = null;
if (authentication == null && tokenUuid != null) {
token = this.userService.findToken(tokenUuid);
authentication = this.userService.authorizeLogin(tokenUuid);
}
if (authentication == null && token == null) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", "requestTrial");
return this.getView(authentication, "/login");
} else {
this.user = UserPrincipal.getUser(authentication);
if (this.user.getSettingAsBoolean("keepSignIn")) {
if (token == null && authentication != null) {
token = (UserToken)authentication.getCredentials();
}
if (token != null) {
Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString());
response.addCookie(cookie);
}
} else {
Cookie cookie = new Cookie("user.token", (String)null);
response.addCookie(cookie);
}
return this.getView(authentication, "/index");
}
}
@RequestMapping(
method = {RequestMethod.OPTIONS, RequestMethod.GET},
path = {"/login/{siteId}"}
)
public String forwardToLogin(@PathVariable String siteId) {
return "redirect:/?siteId=" + siteId;
}
}
@@ -0,0 +1,60 @@
package com.midm.controller;
import com.midm.model.org.User;
import com.midm.model.org.UserToken;
import com.mitac.cell.utils.McUuidUtils;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.NotAcceptableStatusException;
@Controller
public class UserController extends BaseController {
@RequestMapping(
value = {"/resetPassword"},
method = {RequestMethod.GET}
)
public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model, @RequestParam(name = "token") String passwordTokenUid, @RequestParam(required = false) String language) {
this.init(request, response, authentication, language);
model.addAttribute("theme", this.theme);
UUID passwordTokenUuid = McUuidUtils.toUuidFromBase64(passwordTokenUid);
UserToken token = this.userService.findToken(passwordTokenUuid);
if (token != null && token.isExpired()) {
this.userService.deleteTokenByType(token);
}
if (token != null && token.getTokenType() == 'P') {
model.addAttribute("error", false);
User user = this.userService.findUserByUserUuid(token.getUserUuid());
model.addAttribute("token", token);
model.addAttribute("user", user);
return this.getView(authentication, "/resetPassword");
} else {
model.addAttribute("error", true);
return this.getView(authentication, "/resetPassword");
}
}
@RequestMapping(
value = {"/keepSession"},
method = {RequestMethod.GET},
produces = {"text/plain"}
)
@ResponseBody
public String getSettings(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) {
User loggedUser = this.userService.authorizedUser(authentication, accessToken);
if (loggedUser == null) {
throw new NotAcceptableStatusException("");
} else {
return "ok";
}
}
}
@@ -0,0 +1,21 @@
package com.midm.controller.lib;
import com.mitac.cell.barcode.QrCode;
import com.mitac.cell.io.McResource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class BarcodeController {
@RequestMapping(
value = {"/barcode/qr/{code}"},
method = {RequestMethod.GET}
)
public void qrCode(HttpServletResponse response, @PathVariable String code, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, @RequestParam(required = false) Boolean encrypt) {
McResource.copyToResponse(response, QrCode.toImage(code, size, margin));
}
}
@@ -0,0 +1,598 @@
package com.midm.controller.lib;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import com.midm.model.device.Device;
import com.midm.model.file.AppFile;
import com.midm.model.file.BaseFile;
import com.midm.model.org.User;
import com.midm.security.UserPrincipal;
import com.midm.service.cloudStorage.CloudStorageService;
import com.midm.service.device.DeviceService;
import com.midm.service.file.FileService;
import com.midm.service.file.ReportService;
import com.midm.service.store.StoreAppService;
import com.midm.service.store.StoreOtaService;
import com.midm.service.store.StoreOtherService;
import com.mitac.cell.io.McFile;
import com.mitac.cell.io.McResource;
import com.mitac.cell.utils.McUrlUtils;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
@Controller
public class FilesController {
@Autowired
private ServletContext servletContext;
@Autowired
private FileService fileService;
@Autowired
private StoreAppService storeAppService;
@Autowired
private StoreOtaService storeOtaService;
@Autowired
private DeviceService deviceService;
@Autowired
private ReportService reportService;
@Autowired
private StoreOtherService storeOtherService;
@Autowired
private CloudStorageService cloudStorageService;
@RequestMapping(
value = {"userfile/{userUuid}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getUserFile(HttpServletResponse response, Authentication authentication, @PathVariable UUID userUuid, @PathVariable UUID fileUuid, @PathVariable String fileName, @RequestParam(required = false) Long position, @RequestParam(required = false) Long crc32) {
String filePath = this.fileService.getUserFilePath(userUuid, fileUuid);
McFile file = new McFile(filePath);
McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1);
file.delete();
}
@RequestMapping(
value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void geDevicetFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String filePath = this.fileService.getDeviceFilePath(user.getSiteUuid(), deviceUuid, "file", fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"file/{fileType}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileType, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
try {
if (user == null) {
response.sendError(406, "User not logged in.");
return;
}
BaseFile file = this.findFile(response, fileUuid, fileType, true, user.getSiteUuid());
if (file == null || file.hasFileUrl()) {
return;
}
String filePath = this.fileService.getFilePath(user.getSiteUuid(), fileType, fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
} catch (IOException var10) {
}
}
@RequestMapping(
value = {"file/report/template/{fileName}"},
method = {RequestMethod.GET}
)
public void getReportTemplate(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileName) {
String filePath = this.reportService.getTemplateFilePath(fileName);
McFile file = new McFile(filePath);
if (!file.exists()) {
file = this.fileService.getResourceFile("report/" + fileName, false);
}
McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1);
}
@RequestMapping(
value = {"must/reserved/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getMustReservedFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String filePath = this.fileService.getMustDownloadFilePath(user.getSiteUuid(), fileUuid, "region");
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"},
method = {RequestMethod.GET}
)
public void getMustDownloadFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName, @PathVariable String isDirectory) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
boolean isDir = Boolean.parseBoolean(isDirectory);
String path = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String[] tempPath = path.split("/", 7);
String filePath = this.fileService.getMustFolderFilePath(user.getSiteUuid(), fileUuid, tempPath[6]);
if (isDir) {
filePath = this.fileService.getMustDownloadProfilePath(user.getSiteUuid(), fileUuid, "tempDownlad", fileName);
fileName = fileName + ".zip";
}
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getStoreAppFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileType, @PathVariable String packageName, @PathVariable long versionCode, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String filePath = this.storeAppService.getStoreAppPath(packageName, versionCode, fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"store/ota/{productId}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getStoreOtaFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String productId, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String filePath = this.storeOtaService.getStoreOtaFilePath(productId, fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"store/other/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getStoreOtherFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String filePath = this.storeOtherService.getStoreFilePath("other", fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
}
}
@RequestMapping(
value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String siteUuid, @PathVariable String fileType, @PathVariable String fileUuid, @PathVariable String fileName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(name = "position",required = false,defaultValue = "0") Integer from) {
try {
BaseFile file = this.findFile(response, UUID.fromString(fileUuid), fileType, false, UUID.fromString(siteUuid));
if (file == null || file.hasFileUrl()) {
return;
}
String checksum = String.valueOf(file.getChecksum());
if (etag != null && !etag.equals(checksum)) {
range = "";
}
String filePath = this.fileService.getFilePath(siteUuid, fileType, fileUuid);
Integer to = -1;
if (!Strings.isNullOrEmpty(range)) {
range = range.substring(range.indexOf(61) + 1);
if (range.indexOf(44) >= 0) {
response.sendError(400, "Multiple ranges not supported.");
return;
}
boolean isRangeOk = true;
if (range.indexOf(45) >= 0) {
String[] tokens = range.split("-");
if (tokens.length > 0) {
if (Strings.isNullOrEmpty(tokens[0])) {
to = (int)file.getLength() - 1;
from = to - Integer.valueOf(tokens[1]) + 1;
} else {
from = Integer.valueOf(tokens[0]);
if (tokens.length > 1) {
if (Strings.isNullOrEmpty(tokens[1])) {
to = (int)file.getLength() - 1;
} else {
to = Integer.valueOf(tokens[1]);
}
} else {
to = (int)file.getLength() - 1;
}
}
} else {
isRangeOk = false;
}
}
if (!isRangeOk) {
response.sendError(400, "Range is invalid.");
return;
}
}
response.addHeader("ETag", checksum);
response.addHeader("If-Match", checksum);
response.setDateHeader("Last-Modified", file.getLastModified());
response.addHeader("Accept-Ranges", "bytes");
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, from, to);
} catch (Exception var17) {
}
}
@RequestMapping(
value = {"icon/app/{fileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
if (this.cloudStorageService.hasCloudStorage()) {
AppFile file = this.fileService.findApp(fileUuid, true);
if (file.hasIconUrl()) {
try {
String url = file.getIconUrl();
response.sendRedirect(url);
return;
} catch (IOException var11) {
}
}
String url = this.cloudStorageService.getUrl(user.getSiteUuid(), "app", fileUuid + ".png");
if (!Strings.isNullOrEmpty(url)) {
try {
file.setIconUrl(url);
response.sendRedirect(url);
return;
} catch (IOException var10) {
}
}
} else {
String apkPath = this.fileService.getFilePath(user.getSiteUuid(), "app", fileUuid);
McFile iconFile = new McFile(apkPath + ".png");
if (iconFile.exists()) {
byte[] iconData = iconFile.toBytes();
if (iconData != null) {
String var10000 = Files.getNameWithoutExtension(fileName);
fileName = var10000 + (iconData[0] == 60 ? ".svg" : ".png");
fileName = McUrlUtils.encode(fileName);
McResource.copyFileToResponse(this.servletContext, response, iconData, fileName);
return;
}
}
}
this.getMimeIcon(request, response, authentication, "apk");
}
}
@RequestMapping(
value = {"icon/must/app/{profileUuid}/{fileName}"},
method = {RequestMethod.GET}
)
public void getMustSiteAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID profileUuid, @PathVariable String fileName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String iconFilePath = this.fileService.getMustFolderFilePath(user.getSiteUuid(), profileUuid, "apps/" + fileName + ".png");
McFile iconFile = new McFile(iconFilePath);
if (!iconFile.exists()) {
}
byte[] iconData = iconFile.toBytes();
if (iconData != null) {
McResource.copyFileToResponse(this.servletContext, response, iconData, fileName + ".png");
} else {
this.getMimeIcon(request, response, authentication, "apk");
}
}
}
@RequestMapping(
value = {"icon/store/app/{packageName}"},
method = {RequestMethod.GET}
)
public void getStoreAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String packageName) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String iconFilePath = this.storeAppService.getStoreIconPath(packageName);
McFile iconFile = new McFile(iconFilePath);
byte[] iconData = iconFile.toBytes();
if (iconData != null) {
McResource.copyFileToResponse(this.servletContext, response, iconData, packageName + ".png");
} else {
this.getMimeIcon(request, response, authentication, "apk");
}
}
}
@RequestMapping(
value = {"icon/mime/{extension}"},
method = {RequestMethod.GET}
)
public void getMimeIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String extension) {
String resourcePath = Joiner.on('/').join("/image/mime", extension.toLowerCase() + ".png", new Object[0]);
if (!this.fileService.resourceExists(resourcePath, true)) {
resourcePath = "/image/mime/_blank.png";
}
forwardRequest(request, response, resourcePath);
}
@RequestMapping(
value = {"icon/folder/{folderType}"},
method = {RequestMethod.GET}
)
public void getFolderIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String folderType) {
String resourcePath = Joiner.on('/').join("/image/folder", folderType.toLowerCase() + ".png", new Object[0]);
if (!this.fileService.resourceExists(resourcePath, true)) {
resourcePath = "/image/folder/normal.png";
}
forwardRequest(request, response, resourcePath);
}
@RequestMapping(
value = {"profile/user/{userUuid}"},
method = {RequestMethod.GET}
)
public void getUserProfileImage(HttpServletRequest request, HttpServletResponse response, Authentication aHttputhentication, @PathVariable UUID userUuid) {
response.setHeader("Cache-Control", "max-age=2592000");
String profilePath = this.fileService.getUserProfilePath(userUuid);
String fileName = "profile.jpg";
if ((new File(profilePath)).exists()) {
McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1);
} else {
forwardRequest(request, response, "/image/icon/profileUnknown.png");
}
}
@RequestMapping(
value = {"favicon"},
method = {RequestMethod.GET}
)
public void getFavicon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID siteUuid) {
McFile favicon = new McFile(this.fileService.getFaviconPath());
if (favicon.exists()) {
response.setHeader("Cache-Control", "max-age=2592000");
McResource.copyFileToResponse(this.servletContext, response, favicon, favicon.getName(), 0, -1);
} else {
forwardRequest(request, response, "/image/favicon.png");
}
}
@RequestMapping(
value = {"background"},
method = {RequestMethod.GET}
)
public void getBackgroundImage(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID siteUuid) {
if (siteUuid != null) {
String profilePath = this.fileService.getSiteFilePath(siteUuid, "background");
String fileName = "background.jpg";
McFile file = new McFile(profilePath);
if (file.exists()) {
response.setHeader("Cache-Control", "max-age=2592000");
McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "background.jpg", 0, -1);
} else {
forwardRequest(request, response, "/image/bg/background.jpg");
}
} else {
McFile bgFile = new McFile(this.fileService.getBackgroundPath());
if (bgFile.exists()) {
response.setHeader("Cache-Control", "max-age=2592000");
McResource.copyFileToResponse(this.servletContext, response, bgFile, bgFile.getName(), 0, -1);
} else {
forwardRequest(request, response, "/image/bg/background.jpg");
}
}
}
@RequestMapping(
value = {"background/{siteUuid}"},
method = {RequestMethod.GET}
)
public void getSitebackgroundImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) {
this.getSiteImage(request, response, siteUuid, "background");
}
@RequestMapping(
value = {"logo/{siteUuid}"},
method = {RequestMethod.GET}
)
public void getSiteLogoImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) {
this.getSiteImage(request, response, siteUuid, "logo");
}
@RequestMapping(
value = {"profile/site/{siteUuid}"},
method = {RequestMethod.GET}
)
public void getSiteProfileImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) {
this.getSiteImage(request, response, siteUuid, "profile");
}
public void getSiteImage(HttpServletRequest request, HttpServletResponse response, UUID siteUuid, String type) {
if (this.cloudStorageService.hasCloudStorage()) {
String url = this.cloudStorageService.getUrl(siteUuid, type);
if (!Strings.isNullOrEmpty(url)) {
try {
response.sendRedirect(url);
return;
} catch (Exception var10) {
}
}
}
McFile imgFile = new McFile(this.fileService.getSiteFilePath(siteUuid, type));
String fileName = "";
switch (type) {
case "background":
fileName = "backgroud.jpg";
break;
case "logo":
fileName = "logo.png";
break;
case "profile":
fileName = "profile.png";
}
if (imgFile.exists()) {
McResource.copyFileToResponse(this.servletContext, response, imgFile, fileName, 0, -1);
} else if (type.equals("background")) {
this.getBackgroundImage(request, response, (Authentication)null, (UUID)null);
} else if (type.equals("profile")) {
forwardRequest(request, response, "/image/icon/siteUnknown.png");
} else {
try {
response.sendError(404, "Not found.");
} catch (IOException var9) {
}
}
}
@RequestMapping(
value = {"profile/org/{userUuid}"},
method = {RequestMethod.GET}
)
public void getOrgProfileImage(HttpServletResponse response, Authentication authentication, @PathVariable UUID userUuid) {
String profilePath = this.fileService.getFilePath("user", userUuid);
String fileName = "profile.jpg";
McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1);
}
@RequestMapping(
value = {"device/screen/{deviceUuid}"},
method = {RequestMethod.GET}
)
public void getDeviceScreenImage(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid) {
User user = UserPrincipal.getUser(authentication);
if (user != null) {
String profilePath = this.fileService.getDeviceFilePath(user.getSiteUuid(), deviceUuid, "screen", "screen.png");
if (McFile.exists(profilePath)) {
McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "screen.png", 0, -1);
} else {
forwardRequest(request, response, "/image/empty.png");
}
}
}
@RequestMapping(
value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"},
method = {RequestMethod.GET}
)
public void getDeviceFile(HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid, @PathVariable String hostFile, @PathVariable String fileName) {
try {
Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid);
User user = UserPrincipal.getUser(authentication);
if (device != null && user != null && user.isBelongedToSite(device.getSiteUuid())) {
String filePath = this.fileService.getDeviceFilePath(device.getSiteUuid(), deviceUuid, "file", hostFile);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1);
} else {
response.sendError(401, "Not logged in or Unauthorized.");
}
} catch (IOException var9) {
}
}
@RequestMapping(
value = {"file/checksum/{fileUuid}"},
method = {RequestMethod.GET}
)
@ResponseBody
public String getCheckSum(Authentication authentication, @PathVariable UUID fileUuid, @RequestParam(required = false) Integer size) {
User user = UserPrincipal.getUser(authentication);
if (user == null) {
return null;
} else {
String path = this.fileService.getFilePath(user.getSiteUuid(), "other", fileUuid);
McFile file = new McFile(path);
Long checksum = file.getCrcChecksum(size);
return "" + checksum;
}
}
public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) {
try {
if (!response.isCommitted()) {
request.getRequestDispatcher(path).forward(request, response);
}
} catch (IOException | ServletException var6) {
try {
response.sendError(404);
} catch (IOException var5) {
}
}
}
private BaseFile findFile(HttpServletResponse response, UUID fileUuid, String fileType, boolean minify, UUID siteUuid) {
BaseFile file = null;
switch (fileType) {
case "app":
file = this.fileService.findApp(fileUuid, minify);
break;
case "ota":
file = this.fileService.findOta(fileUuid);
break;
case "other":
file = this.fileService.findFile(fileUuid);
break;
case "report":
file = this.reportService.findReportByUuid(fileUuid);
}
try {
if (file == null) {
response.sendError(404);
} else if (file.hasFileUrl()) {
response.sendRedirect(file.getFileUrl());
} else if (this.cloudStorageService.hasCloudStorage()) {
String url = this.cloudStorageService.getUrl(siteUuid, fileType, fileUuid);
if (!Strings.isNullOrEmpty(url)) {
file.setCloudUrl(url);
response.sendRedirect(url);
}
}
} catch (Exception var9) {
}
return file;
}
}
@@ -0,0 +1,81 @@
package com.midm.controller.lib;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import com.midm.controller.BaseController;
import com.mitac.cell.internet.http.McResponse;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ResourceController extends BaseController {
@RequestMapping(
value = {"/js/**", "/css/**"},
method = {RequestMethod.GET}
)
public String getScript(HttpServletRequest request, Authentication authentication) {
return this.getResource(authentication, request.getServletPath());
}
@RequestMapping(
value = {"js/controller/login.js"},
method = {RequestMethod.GET},
produces = {"application/javascript"}
)
public String getLoginScript(HttpServletRequest request, Model model, Authentication authentication, @RequestHeader("host") String hostHeader, @RequestParam(required = false) String hostParam, @RequestParam(required = false,defaultValue = "login") String pageFor) {
model.addAttribute("hasUser", this.userService.hasUser());
model.addAttribute("pageFor", pageFor);
return this.getResource(authentication, request.getServletPath());
}
@RequestMapping(
value = {"/js/controller/resetPassword.js"},
method = {RequestMethod.GET},
produces = {"application/javascript"}
)
public String getResetPasswordScript(HttpServletRequest request, Model model, Authentication authentication, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) UUID tokenUuid) {
model.addAttribute("error", userUuid == null);
model.addAttribute("tokenUuid", tokenUuid);
model.addAttribute("userUuid", userUuid);
return this.getResource(authentication, request.getServletPath());
}
@RequestMapping(
value = {"img/**"},
method = {RequestMethod.GET}
)
@ResponseBody
public ResponseEntity getImage(HttpServletRequest request, Authentication authentication) {
String path = this.getTemplateResource(authentication, request.getServletPath());
return this.getServletResource(request, path);
}
@RequestMapping(
value = {"images/**"},
method = {RequestMethod.GET}
)
@ResponseBody
public ResponseEntity getImages(HttpServletRequest request, Authentication authentication) {
String path = this.getTemplateResource(authentication, "/img" + request.getServletPath());
return this.getServletResource(request, path);
}
private ResponseEntity getServletResource(HttpServletRequest request, String path) {
String subType = Files.getFileExtension(path);
if (Strings.isNullOrEmpty(subType)) {
subType = "jpg";
}
return McResponse.getServletResource(request, new MediaType("image", subType), path);
}
}
@@ -0,0 +1,320 @@
package com.midm.controller.lib;
import com.google.common.base.Strings;
import com.midm.model.store.AppReleaseNote;
import com.midm.model.store.KeyStore;
import com.midm.model.store.StoreApp;
import com.midm.model.store.StoreAppFile;
import com.midm.model.store.StoreOtaFile;
import com.midm.model.store.StoreOtherFile;
import com.midm.model.store.StoreWebApp;
import com.midm.service.cloudStorage.CloudStorageService;
import com.midm.service.file.FileService;
import com.midm.service.store.KeyStoreService;
import com.midm.service.store.StoreAppService;
import com.midm.service.store.StoreOtaService;
import com.midm.service.store.StoreOtherService;
import com.midm.service.store.StoreWebAppService;
import com.midm.service.system.HostLicenseService;
import com.mitac.cell.io.McFile;
import com.mitac.cell.io.McResource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
@Controller
@RequestMapping({"store"})
public class StoreController {
@Autowired
private ServletContext servletContext;
@Autowired
private StoreAppService storeAppService;
@Autowired
private StoreOtaService storeOtaService;
@Autowired
private StoreWebAppService storeWebAppService;
@Autowired
@Qualifier("stringTemplateEngine")
private TemplateEngine stringTemplateEngine;
@Autowired
private KeyStoreService keyStoreService;
@Autowired
private StoreOtherService storeOtherService;
@Autowired
private FileService fileService;
@Autowired
private CloudStorageService cloudStorageService;
@Autowired
@Lazy
private HostLicenseService hostLicenseService;
@RequestMapping(
value = {"apps/download/{packageName}"},
method = {RequestMethod.GET}
)
public void getLatestApp(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(name = "checksum",required = false) String certMd5, @RequestParam(name = "keyStore",required = false) String keyStoreId, @RequestParam(required = false,defaultValue = "-1") int versionCode) {
if (Strings.isNullOrEmpty(certMd5) && !Strings.isNullOrEmpty(keyStoreId)) {
if (keyStoreId.equals("default")) {
keyStoreId = "android_default";
}
KeyStore keyStore = this.keyStoreService.find(keyStoreId);
certMd5 = keyStore.getCertMd5();
}
this.getApp(request, response, range, etag, packageName, String.valueOf(versionCode), keyStoreId, -1);
}
@RequestMapping(
value = {"apps/{packageName}/{version}/{keyStoreId}"},
method = {RequestMethod.GET}
)
public void getApp(HttpServletRequest request, HttpServletResponse response, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @PathVariable String packageName, @PathVariable String version, @PathVariable String keyStoreId, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) {
if (Strings.isNullOrEmpty(keyStoreId) || keyStoreId.equals("default")) {
keyStoreId = "android_default";
}
KeyStore keyStore = this.keyStoreService.find(keyStoreId);
if (keyStore == null) {
try {
response.sendError(404, "No key store exists.");
} catch (IOException var14) {
}
} else {
String certMd5 = keyStore.getCertMd5();
StoreAppFile appFile = null;
if (version.equalsIgnoreCase("latest")) {
appFile = this.storeAppService.findLatestAppFile(packageName, -1, sdkVersion, certMd5);
} else {
try {
long versionCode = Long.parseLong(version);
appFile = this.storeAppService.findAppFile(packageName, versionCode, certMd5);
} catch (Exception var16) {
}
}
if (appFile != null) {
this.getApp(response, appFile, range);
} else {
try {
response.sendError(404, "No apps found.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@RequestMapping(
value = {"app/{fileUuid}"},
method = {RequestMethod.GET}
)
public void getApp(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) {
StoreAppFile appFile = this.storeAppService.findAppFile(fileUuid);
if (appFile == null) {
try {
response.sendError(404, "App file not exists.");
} catch (IOException e) {
e.printStackTrace();
}
} else {
this.getApp(response, appFile, range);
}
}
private void getApp(HttpServletResponse response, StoreAppFile appFile, String range) {
String url = this.cloudStorageService.getUrl("store", "app", appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid());
if (Strings.isNullOrEmpty(url)) {
String filePath = this.storeAppService.getStoreAppPath(appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid());
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), appFile.getFileName(), appFile.getLastModified(), range, appFile.getChecksum());
} else {
try {
response.sendRedirect(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@RequestMapping(
value = {"apps/{packageName}/releaseNote"},
method = {RequestMethod.GET}
)
@ResponseBody
public String appReleaseNote(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) throws IOException {
return this.appReleaseNote(request, response, packageName, (String)null, (Integer)null, sdkVersion, true);
}
@RequestMapping(
value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"},
method = {RequestMethod.GET}
)
@ResponseBody
public String appReleaseNote(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @PathVariable String keyStore, @PathVariable(required = false) Integer pathSdkVersion, @RequestParam(required = false,defaultValue = "-1") int sdkVersion, @RequestParam(required = false,defaultValue = "1") Boolean isFormal) throws IOException {
WebContext context = new WebContext(request, response, this.servletContext, request.getLocale());
StoreApp app = this.storeAppService.find(packageName);
if (pathSdkVersion != null) {
sdkVersion = pathSdkVersion;
}
List<AppReleaseNote> notes = this.storeAppService.findReleaseNotes(packageName, sdkVersion, isFormal == null ? null : true);
context.setVariable("app", app);
context.setVariable("fixedKeyStores", Arrays.asList("mio", "default"));
if (!Strings.isNullOrEmpty(keyStore)) {
context.setVariable("keyStore", keyStore);
}
context.setVariable("notes", notes);
List<Integer> sdkVersions = this.storeAppService.getSdkVersions(packageName);
List<String> sdkVersionsStr = (List)sdkVersions.stream().map(String::valueOf).collect(Collectors.toList());
sdkVersionsStr.add(0, "All");
context.setVariable("sdkVersions", sdkVersionsStr);
context.setVariable("selectedSdk", String.valueOf(sdkVersion));
String helpTemplate = this.fileService.getResourceToString("help/app.releaseNote.html", false);
String result = this.stringTemplateEngine.process(helpTemplate, context);
return result;
}
@RequestMapping(
value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"},
method = {RequestMethod.GET}
)
@ResponseBody
public String appReleaseNoteShowAll(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @PathVariable String keyStore, @PathVariable(required = false) Integer pathSdkVersion, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) throws IOException {
return this.appReleaseNote(request, response, packageName, keyStore, pathSdkVersion, sdkVersion, (Boolean)null);
}
@RequestMapping(
value = {"ota/{fileUuid}"},
method = {RequestMethod.GET}
)
public void getOta(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) {
StoreOtaFile otaFile = this.storeOtaService.findOtaFile(fileUuid);
try {
if (otaFile == null) {
response.sendError(404, "System update file not exists.");
} else {
String url = this.cloudStorageService.getUrl("store", "ota", otaFile.getProductId(), fileUuid);
if (Strings.isNullOrEmpty(url)) {
String filePath = this.storeOtaService.getStoreOtaFilePath(otaFile.getProductId(), fileUuid);
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), otaFile.getFileName(), otaFile.getLastModified(), range, otaFile.getChecksum());
} else {
response.sendRedirect(url);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(
value = {"webapp/{fileUuid}"},
method = {RequestMethod.GET}
)
public void getWebApp(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) throws IOException {
StoreWebApp app = null;
try {
app = this.storeWebAppService.find(UUID.fromString(fileUuid));
} catch (Exception var10) {
app = this.storeWebAppService.find((String)null, (String)null, fileUuid);
}
this.getWebApp(response, app, range);
}
@RequestMapping(
value = {"webapp/latest"},
method = {RequestMethod.GET}
)
public void getWebApp(HttpServletRequest request, HttpServletResponse response, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false,defaultValue = "true") boolean isFormal) throws IOException {
StoreWebApp app = this.storeWebAppService.findLatest(groupId, artifactId, isFormal);
this.getWebApp(response, app, range);
}
private void getWebApp(HttpServletResponse response, StoreWebApp app, String range) {
try {
if (app != null) {
String url = this.cloudStorageService.getUrl("store", "webapp", app.getFileUuid());
if (Strings.isNullOrEmpty(url)) {
String filePath = this.storeWebAppService.getStoreFilePath(app.getFileUuid());
McFile file = new McFile(filePath);
if (file.exists()) {
McResource.copyFileToResponse(this.servletContext, response, file, app.getFileName(), app.getLastModified(), range, app.getChecksum());
} else {
response.sendError(404, "Webapp file not exists.");
}
} else {
response.sendRedirect(url);
}
} else {
response.sendError(404, "Webapp file not exists.");
}
} catch (IOException var7) {
}
}
@RequestMapping(
value = {"webapp/releaseNote"},
method = {RequestMethod.GET}
)
@ResponseBody
public String webAppReleaseNote(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false) String version, @RequestParam(required = false,defaultValue = "0") int limit, @RequestParam(required = false,defaultValue = "true") boolean isFormal) throws IOException {
List<StoreWebApp> webapp = this.storeWebAppService.findAll(groupId, artifactId, version, limit);
WebContext context = new WebContext(request, response, this.servletContext, request.getLocale());
context.setVariable("title", "MiDM Host Release Note");
context.setVariable("apps", webapp);
context.setVariable("isFormal", isFormal);
String helpTemplate = this.fileService.getResourceToString("help/webapp.releaseNote.html", false);
String result = this.stringTemplateEngine.process(helpTemplate, context);
return result;
}
@RequestMapping(
value = {"other/{fileName}"},
method = {RequestMethod.GET}
)
public void getOtherFile(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) {
StoreOtherFile file = this.storeOtherService.findByUuidOrNameOrAlias(fileName);
try {
if (file == null) {
response.sendError(404, "System update file not exists.");
} else {
String url = this.cloudStorageService.getUrl("store", "other", file.getFileUuid());
if (Strings.isNullOrEmpty(url)) {
String filePath = this.storeOtherService.getStoreFilePath("other", file.getFileUuid());
McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), file.getFileName(), file.getLastModified(), range, file.getChecksum());
} else {
response.sendRedirect(url);
}
}
} catch (IOException var11) {
}
}
}
@@ -0,0 +1,161 @@
package com.midm.dpc;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.midm.model.message.MidmResponse;
import com.midm.model.org.Site;
import com.midm.model.org.SiteInfo;
import com.midm.model.org.User;
import com.midm.model.store.StoreAppFile;
import com.midm.service.org.SiteService;
import com.midm.service.org.UserService;
import com.midm.service.store.StoreAppService;
import com.mitac.cell.barcode.QrCode;
import com.mitac.cell.io.McResource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponentsBuilder;
/**
* ======================================================================================
* Android Enterprise 设备策略控制器配置与零接触二维码生成器 (DpcController)
* ======================================================================================
*
* <p>【Android Enterprise / 谷歌企业移动管理 (EMM) 规范实现】
* 1. 业务场景(零接触配置与开箱即用 - Zero-Touch Enrollment):
* - 当企业采购批量的全新 Android 手持终端/平板开机时,在开机欢迎界面连续点击 6 次,
* 系统将自动唤起系统级摄像头扫描器;
* - 扫描由本控制器 {@link #qrCode} 生成的特制二维码,即可实现无人工干预的静默绑定。
* 2. 【DPC 配置规范 (Provisioning Bundle)】:
* - 动态组装包含应用下载地址、SHA-256 校验哈希(Checksum)、
* DeviceAdminReceiver 组件名称及企业 Wi-Fi 预置参数的 JSON 捆绑包;
* - 设备扫描后,Android 操作系统会自动静默下载 DPC 客户端并将其提权激活为设备所有者(Device Owner),
* 获得最高系统级管控权限(如锁屏禁用、静默安装、Kiosk单应用专机模式)。
*
* @author MiDM Core Platform Team
*/
@Controller
public class DpcController {
@Autowired
private StoreAppService storeAppService;
@Autowired
private UserService userService;
@Autowired
private SiteService siteService;
/**
* 生成供 Android 设备开箱扫描的 DPC 零接触配置二维码图片流
*
* @param request HTTP 请求
* @param response HTTP 响应(直接输出 PNG 图像二进制流)
* @param size 图像尺寸大小
* @param margin 图像白边边距
* @param dpc DPC 参数载荷模型
*/
@RequestMapping(
value = {"/dpc/qr"},
method = {RequestMethod.GET}
)
public void qrCode(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, DpcModel dpc) {
this.toDpcConfig(request, dpc);
McResource.copyToResponse(response, QrCode.toImage(dpc.toDpcConfig(), size, margin));
}
/**
* 获取 JSON 格式的 DPC 原生配置文本(供批量打单或定制初始化应用提取)
*/
@RequestMapping(
value = {"/dpc/config"},
method = {RequestMethod.GET}
)
@ResponseBody
public String intent(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, DpcModel dpc) {
return this.toDpcConfig(request, dpc);
}
private String toDpcConfig(HttpServletRequest request, DpcModel dpc) {
String adminPackage = dpc.getDeviceAdmin();
if (!Strings.isNullOrEmpty(adminPackage) && adminPackage.indexOf(47) < 0) {
if (adminPackage.equals("com.mitac.midm.dpc")) {
dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MidmDeviceAdminReceiver"}));
StoreAppFile appFile = this.storeAppService.findLatestAppFile(adminPackage, -1, -1, (String)null);
if (appFile != null) {
String filePath = this.storeAppService.getStoreAppPath(adminPackage, appFile.getVersionCode(), appFile.getFileUuid());
dpc.setPackageChecksum(DpcUtils.getChecksum(new File(filePath)));
}
String downloadUrl = dpc.getDownloadUrl();
if (Strings.isNullOrEmpty(downloadUrl)) {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequestUri(request).replacePath(Joiner.on("").join(request.getContextPath(), "/store/apps/download/", new Object[]{adminPackage}));
if (builder.build().getHost().endsWith("mic.com.tw")) {
builder.scheme("https");
}
downloadUrl = builder.build().toUriString();
dpc.setDownloadUrl(downloadUrl);
}
} else if (adminPackage.equals("com.mitac.must.service")) {
dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MustDeviceAdminReceiver"}));
} else if (adminPackage.equals("com.mitac.midm.system")) {
dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MidmDeviceAdminReceiver"}));
}
}
if (!Strings.isNullOrEmpty(dpc.getDownloadUrl()) && Strings.isNullOrEmpty(dpc.getPackageChecksum())) {
try {
URL url = new URL(dpc.getDownloadUrl());
dpc.setPackageChecksum(DpcUtils.getChecksum(url));
} catch (MalformedURLException var13) {
}
}
DpcModel.MidmConfig midmConfig = dpc.getMidm();
if (midmConfig != null) {
String email = midmConfig.getEmail();
String password = midmConfig.getPassword();
String siteModel = midmConfig.getSiteId();
if (!Strings.isNullOrEmpty(siteModel) && !Strings.isNullOrEmpty(email) && !Strings.isNullOrEmpty(password)) {
User user = this.userService.findUserByEmail(email);
if (user != null && this.userService.matchPassword(user, password)) {
for(SiteInfo siteInfo : user.getSites()) {
UUID siteUuid = siteInfo.getSiteUuid();
Site site = this.siteService.findByUuid(siteUuid);
if (site != null && siteModel.equals(site.getModel())) {
midmConfig.setSiteId(siteUuid.toString());
midmConfig.setEmail((String)null);
midmConfig.setPassword((String)null);
break;
}
}
}
}
}
return dpc.toDpcConfig();
}
@RequestMapping(
value = {"/dpc/checksum"},
method = {RequestMethod.GET}
)
@ResponseBody
public String getChecksum(HttpServletRequest request, HttpServletResponse response, @RequestParam String url) {
try {
String checksum = DpcUtils.getChecksum(new URL(url));
return MidmResponse.getSucceedResponse((Object)checksum);
} catch (MalformedURLException var5) {
return MidmResponse.getFailedResponse();
}
}
}
+280
View File
@@ -0,0 +1,280 @@
package com.midm.dpc;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.springframework.security.crypto.password.PasswordEncoder;
public class DpcModel {
public static final String COMPONENT_MUST_SERVICE = "com.mitac.must.service/com.mitac.must.service.MustDeviceAdminReceiver";
public static final String COMPONENT_MIDM_DPC = "com.mitac.midm.dpc/com.mitac.midm.dpc.MidmDeviceAdminReceiver";
@SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_SSID",
alternate = {"ssid"}
)
private String ssid;
@SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE",
alternate = {"security"}
)
private String security;
@SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_PASSWORD",
alternate = {"password"}
)
private String password;
@SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_HIDDEN",
alternate = {"hidden"}
)
private Boolean hidden;
@SerializedName(
value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED",
alternate = {"enableAllSystemApps"}
)
private boolean enableAllSystemApps = true;
@SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME",
alternate = {"deviceAdmin"}
)
private String deviceAdmin;
@SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM",
alternate = {"packageChecksum"}
)
private String packageChecksum;
@SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION",
alternate = {"downloadUrl"}
)
private String downloadUrl;
@SerializedName(
value = "android.app.extra.PROVISIONING_LOCALE",
alternate = {"locale"}
)
private String locale;
@SerializedName(
value = "android.app.extra.PROVISIONING_TIME_ZONE",
alternate = {"timeZone"}
)
private String timeZone;
@SerializedName(
value = "android.app.extra.PROVISIONING_LOCAL_TIME",
alternate = {"localTime"}
)
private String localTime;
@SerializedName(
value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE",
alternate = {"midm"}
)
private MidmConfig midmConfig;
public String getSsid() {
return this.ssid;
}
public void setSsid(String ssid) {
this.ssid = ssid;
}
public String getSecurity() {
return this.security;
}
public void setSecurity(String securityType) {
this.security = securityType;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public void encryptPassword(PasswordEncoder passwordEncoder) {
if (this.midmConfig != null && !Strings.isNullOrEmpty(this.midmConfig.getPassword())) {
this.midmConfig.setPassword(passwordEncoder.encode(this.midmConfig.getPassword()));
}
}
public boolean hidden() {
return this.hidden;
}
public void setHidden(boolean isHidden) {
this.hidden = isHidden;
}
public boolean isEnableAllSystemApps() {
return this.enableAllSystemApps;
}
public void setEnableAllSystemApps(boolean enableAllSystemApps) {
this.enableAllSystemApps = enableAllSystemApps;
}
public String getDeviceAdmin() {
return this.deviceAdmin;
}
public void setDeviceAdmin(String deviceAdmin) {
this.deviceAdmin = deviceAdmin;
}
public String getDeviceAdminPackageName() {
if (Strings.isNullOrEmpty(this.deviceAdmin)) {
return null;
} else {
int indexSlash = this.deviceAdmin.indexOf(47);
return indexSlash < 0 ? this.deviceAdmin : this.deviceAdmin.substring(0, this.deviceAdmin.indexOf(47));
}
}
public String getPackageChecksum() {
return this.packageChecksum;
}
public void setPackageChecksum(String packageChecksum) {
this.packageChecksum = packageChecksum;
}
public String getDownloadUrl() {
return this.downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public String getLocale() {
return this.locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public MidmConfig getMidm() {
return this.midmConfig;
}
public void setMidm(MidmConfig midm) {
this.midmConfig = midm;
}
public String toDpcConfig() {
Gson gson = (new GsonBuilder()).disableHtmlEscaping().create();
return gson.toJson(this);
}
public static class MidmConfig {
@SerializedName(
value = "midm.host.url",
alternate = {"hostUrl"}
)
private String hostUrl;
@SerializedName(
value = "midm.app.client.url",
alternate = {"clientAppUrl"}
)
private String clientAppUrl;
@SerializedName(
value = "midm.app.system.url",
alternate = {"systemAppUrl"}
)
private String systemAppUrl;
@SerializedName(
value = "midm.app.install.latest",
alternate = {"updateLatest"}
)
private Boolean updateLatest;
@SerializedName(
value = "midm.app.install.slient",
alternate = {"installSilent"}
)
private Boolean installSilent;
@SerializedName(
value = "midm.site",
alternate = {"siteId"}
)
private String siteId;
@SerializedName(
value = "midm.email",
alternate = {"email"}
)
private String email;
@SerializedName(
value = "midm.password",
alternate = {"password"}
)
private String password;
public String getHostUrl() {
return this.hostUrl;
}
public void setHostUrl(String url) {
this.hostUrl = url;
}
public String getClientAppUrl() {
return this.clientAppUrl;
}
public void setClientAppUrl(String clientAppUrl) {
this.clientAppUrl = clientAppUrl;
}
public String getSystemAppUrl() {
return this.systemAppUrl;
}
public void setSystemAppUrl(String systemAppUrl) {
this.systemAppUrl = systemAppUrl;
}
public Boolean getUpdateLatest() {
return this.updateLatest;
}
public void setUpdateLatest(Boolean updateLatest) {
this.updateLatest = updateLatest;
}
public Boolean getInstallSilent() {
return this.installSilent;
}
public void setInstallSilent(Boolean installSilent) {
this.installSilent = installSilent;
}
public String getSiteId() {
return this.siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
+36
View File
@@ -0,0 +1,36 @@
package com.midm.dpc;
import com.mitac.cell.io.McFile;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import org.apache.commons.io.IOUtils;
public class DpcUtils {
public static String getChecksum(URL url) {
try {
return getChecksum(IOUtils.toByteArray(url.openStream()));
} catch (IOException var2) {
return null;
}
}
public static String getChecksum(File file) {
return !file.exists() ? null : getChecksum((new McFile(file)).toBytes());
}
public static String getChecksum(byte[] bytes) {
try {
MessageDigest shaDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = shaDigest.digest(bytes);
String checksum = Base64.getEncoder().withoutPadding().encodeToString(hash);
checksum = checksum.replaceAll("[+]", "-").replaceAll("/", "_");
return checksum;
} catch (NoSuchAlgorithmException var4) {
return null;
}
}
}
@@ -0,0 +1,241 @@
package com.midm.model;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McBooleanUtils;
import com.mitac.cell.utils.McDateTimeUtils;
import java.util.Date;
import java.util.UUID;
import org.bson.Document;
import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
public class GeneralProfile {
@Id
protected UUID uuid;
protected DbObject profile;
protected DbObject settings;
protected Date created;
@Indexed
protected Date updated;
protected Boolean enabled;
public void init() {
this.generateId();
this.created = new Date();
this.updated = this.created;
}
public void generateId() {
this.uuid = UUID.randomUUID();
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public DbObject getProfile() {
if (this.profile == null) {
this.profile = new DbObject();
}
return this.profile;
}
public void setProfile(DbObject profile) {
this.profile = profile;
}
public DbObject getSettings() {
if (this.settings == null) {
this.settings = new DbObject();
}
return this.settings;
}
public void setSettings(DbObject settings) {
this.settings = settings;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return this.updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public void setUpdated() {
this.setUpdated(new Date());
}
public boolean getEnabled() {
return this.enabled != null && this.enabled;
}
public boolean isEnded() {
if ("ends".equals(this.getProfile("endsOption"))) {
DateTime dateTime = McDateTimeUtils.parseDate((String)this.getProfile("ends"), "yyyy-MM-dd").plusDays(1);
return dateTime.isBeforeNow();
} else {
return false;
}
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Object getProfile(String key) {
return this.getProfile(key, (Object)null);
}
public Object getProfile(String key, Object defaultValue) {
if (this.getProfile().containsKey(key)) {
try {
return this.getProfile().get(key);
} catch (Exception var4) {
}
}
return defaultValue;
}
public boolean getProfileAsBoolean(String category, String key, String subCategory, String item, boolean def) {
Boolean value = McBooleanUtils.isTrue(this.getProfile(category, key, subCategory, item));
return value == null ? def : value;
}
public Object getProfile(String category, String key, String subCategory, String item) {
return this.getProfileCategory(category, key, subCategory).get(item);
}
public DbObject getProfileCategory(String... categoryNames) {
return this.getProfile().getDbObject(categoryNames);
}
public Object getCategoryProfile(String category, String key) {
return this.getProfileCategory(category) == null ? null : this.getProfileCategory(category).get(key);
}
public void setProfile(String key, Object value) {
this.getProfile().put(key, value);
}
public void setProfile(String category, String key, Object value) {
this.getProfileCategory(category).put(key, value);
}
public void setProfile(String category, String subCategory, String item, String key, Object value) {
this.getProfileCategory(category, subCategory, item).put(key, value);
}
public void removeProfile(String key) {
if (this.profile != null) {
this.profile.remove(key);
}
}
public Object getSetting(String key) {
return this.getSettings().get(key);
}
public String getSettingAsString(String key) {
return this.getSettings().getString(key, (String)null);
}
public int getSettingAsInt(String key, int def) {
return this.getSettings().getInteger(key, def);
}
public float getSettingAsFloat(String key, float def) {
return this.getSettings().getFloat(key, def);
}
public boolean getSettingAsBoolean(String key) {
return this.getSettingAsBoolean(key, false);
}
public boolean getSettingAsBoolean(String key, boolean def) {
return this.getSettings().containsKey(key) ? McBooleanUtils.isTrue(this.getSetting(key)) : def;
}
public boolean getSettingAsBoolean(String category, String key, boolean def) {
Boolean value = McBooleanUtils.isTrue(this.getSetting(category, key));
return value == null ? def : value;
}
public UUID getSettingAsUuid(String key) {
return this.getSettings().getUuid(key);
}
public DbObject getSettingsCategory(String... categoryNames) {
return this.getSettings().getDbObject(categoryNames);
}
public Object getSetting(String category, String key) {
return this.getSettingsCategory(category).get(key);
}
public void setSetting(String key, UUID value) {
if (value != null) {
this.getSettings().put(key, value.toString());
} else {
this.getSettings().remove(key);
}
}
public void setSetting(String key, Object value) {
this.getSettings().put(key, value);
}
public void setSetting(String categoryName, String key, Object value) {
Document dbObject = this.getSettingsCategory(categoryName);
if (value != null) {
dbObject.put(key, value);
} else {
dbObject.remove(key);
}
}
public void removeOption(String key) {
this.getSettings().remove(key);
}
public String getName() {
Object value = this.getProfile("name");
return value == null ? null : (String)value;
}
public void setName(String name) {
this.setProfile("name", name);
}
public String getDescription() {
return (String)this.getProfile("desc");
}
public void setDescription(String desc) {
this.setProfile("desc", desc);
}
public void minify() {
this.created = null;
}
}
@@ -0,0 +1,26 @@
package com.midm.model;
public class GroupByResult {
private String[] groups;
private int count;
public int getCount() {
return this.count;
}
public void setCount(int count) {
this.count = count;
}
public String getGroup() {
return this.groups.length > 0 ? this.groups[0] : null;
}
public String[] getGroups() {
return this.groups;
}
public void setGroups(String[] groups) {
this.groups = groups;
}
}
@@ -0,0 +1,31 @@
package com.midm.model;
import com.google.common.base.CharMatcher;
public enum IF_EXISTS_OPTION {
ignore(0),
skip(0),
replace(1),
overwrite(1),
update(2),
modify(2),
remove(3);
public int option;
private IF_EXISTS_OPTION(int option) {
this.option = option;
}
public static IF_EXISTS_OPTION get(String key) {
try {
return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase());
} catch (Exception var2) {
return skip;
}
}
public static int getOption(String option) {
return get(option).option;
}
}
@@ -0,0 +1,126 @@
package com.midm.model.battery;
import com.google.gson.reflect.TypeToken;
import com.midm.model.GeneralProfile;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndexes({@CompoundIndex(
def = "{'profile.hardware_info.batterySerial':1}",
unique = true
)})
public class Battery extends GeneralProfile {
private UUID siteUuid;
private DbObject states;
@Transient
private String deviceGroupPath;
public Battery() {
this.init();
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public String getBatterySerial() {
return (String)this.getCategoryProfile("hardware_info", "batterySerial");
}
public String getDeviceSerial() {
return (String)this.getCategoryProfile("hardware_info", "deviceSerial");
}
public void setDeviceSerial(String deviceSerial) {
this.setProfile("hardware_info", "deviceSerial", deviceSerial.trim());
}
public String getModel() {
return (String)this.getCategoryProfile("hardware_info", "model");
}
public String getDeviceId() {
return (String)this.getCategoryProfile("hardware_info", "device_id");
}
public void setRegisterState(String state) {
this.getStates().put("state", state);
}
public String getRegisterState() {
return this.getStates().getString("state");
}
public Integer getBatteryCondition() {
return this.getStates().getInteger("batteryCondition", -1);
}
public DbObject getStates() {
if (this.states == null) {
this.states = new DbObject();
}
return this.states;
}
public String getDeviceGroupPath() {
return this.deviceGroupPath;
}
public void setDeviceGroupPath(String deviceGroupPath) {
this.deviceGroupPath = deviceGroupPath;
}
public ValueWithTime getLastTemp() {
List<ValueWithTime> dbTempList = (List)McJsonUtils.toObject(McJsonUtils.toJson(this.getStates().get("temperature")), (new TypeToken() {
}).getType());
return dbTempList.isEmpty() ? null : (ValueWithTime)dbTempList.get(0);
}
public void setLastTemp(ValueWithTime t) {
DbObject obj = new DbObject();
obj.append("reportedAt", t.getReportedAt()).append("value", t.getValue());
List<DbObject> list = new ArrayList();
list.add(obj);
this.getStates().put("temperature", list);
}
public static enum BATTERY_CONDITION {
UNKNOWN(-1),
GOOD(0),
AVERAGE(1),
SERVICE_SOON(2);
private int value;
private BATTERY_CONDITION(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static BATTERY_CONDITION forValue(int value) {
for(BATTERY_CONDITION e : values()) {
if (e.value == value) {
return e;
}
}
return UNKNOWN;
}
}
}
@@ -0,0 +1,51 @@
package com.midm.model.battery;
import com.mitac.cell.db.DbObject;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndex(
def = "{batterySerial: 1, reportedAt: 1}"
)
public class BatteryLog {
@Id
private UUID uuid = UUID.randomUUID();
@Indexed
private String batterySerial;
@Indexed
private String category;
private String log;
@Indexed
private Date reportedAt;
private DbObject states;
private Date recordedAt = new Date();
public UUID getUuid() {
return this.uuid;
}
public String getBatterySerial() {
return this.batterySerial;
}
public void setCategory(String category) {
this.category = category;
}
public DbObject getStates() {
if (this.states == null) {
this.states = new DbObject();
}
return this.states;
}
public Date getReportedAt() {
return this.reportedAt;
}
}
@@ -0,0 +1,29 @@
package com.midm.model.battery;
import java.util.Date;
public class ValueWithTime {
private Date reportedAt;
private double value;
public ValueWithTime(Date reportedAt, double value) {
this.reportedAt = reportedAt;
this.value = value;
}
public Date getReportedAt() {
return this.reportedAt;
}
public void setReportedAt(Date reportedAt) {
this.reportedAt = reportedAt;
}
public double getValue() {
return this.value;
}
public void setValue(double value) {
this.value = value;
}
}
@@ -0,0 +1,91 @@
package com.midm.model.device;
import com.google.common.base.Strings;
public class AppInfo {
private String packageName;
private String label;
private String versionName;
private Integer versionCode;
private Integer minSdkVersion;
private Long appSize;
private Long dataSize;
private Long firstInstalled;
private Long lastUpdated;
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getLabel() {
return Strings.isNullOrEmpty(this.label) ? this.packageName : this.label;
}
public void setLabel(String label) {
this.label = label;
}
public String getVersionName() {
return this.versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public int getVersionCode() {
return this.versionCode;
}
public void setVersionCode(int versionCode) {
this.versionCode = versionCode;
}
public int minSdkVersion() {
return this.minSdkVersion;
}
public void setMinSdkVersion(int version) {
this.minSdkVersion = version;
}
public long getAppSize() {
return this.appSize;
}
public void setAppSize(long appSize) {
this.appSize = appSize;
}
public long getDataSize() {
return this.dataSize;
}
public void setDataSize(long dataSize) {
this.dataSize = dataSize;
}
public long getFirstInstalled() {
return this.firstInstalled;
}
public void setFirstInstalled(long firstInstalled) {
this.firstInstalled = firstInstalled;
}
public long getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String toString() {
return String.format("%s %s(%s)", this.label, this.versionName, this.packageName);
}
}
@@ -0,0 +1,51 @@
package com.midm.model.device;
import com.google.common.base.CharMatcher;
public enum DEVICE_PROPERTY {
serialno,
serial_no,
serialnumber,
serial_number,
productsn,
product_sn,
partno,
partnumber,
part_no,
palletno,
pallet_no,
cartonsn,
carton_sn,
wifimac,
wifi_mac,
device_group,
devicegroup,
group,
owner,
owner_name,
owner_email,
owner_phone,
owner_mobile,
email,
description,
desc,
comment,
memo,
exists,
ifexists,
if_exists,
license,
renew,
renewtosamemodel,
renew_to_same_model,
rsa,
unknown;
public static DEVICE_PROPERTY get(String key) {
try {
return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase());
} catch (Exception var2) {
return unknown;
}
}
}
@@ -0,0 +1,137 @@
package com.midm.model.device;
import com.mitac.cell.db.DbObject;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndex(
def = "{deviceUuid: 1, siteUuid: 1}"
)
public class DataUsage {
@Id
private UUID uuid;
private UUID deviceUuid;
private UUID siteUuid;
@Indexed
private Date from;
@Indexed
private Date to;
private DbObject usage;
@Indexed(
expireAfterSeconds = 15552000
)
private Date recordedAt;
public DataUsage() {
this.uuid = UUID.randomUUID();
this.recordedAt = new Date();
}
public DataUsage(Device device, DbObject report) {
this();
this.setSiteUuid(device.getSiteUuid());
this.setDeviceUuid(device.getUuid());
this.usage = report;
DbObject wifiProperty = report.getDbObject(new String[]{"wifi"});
DbObject mobileProperty = report.getDbObject(new String[]{"mobile"});
long from = mobileProperty.getLong("from", wifiProperty.getLong("from"));
this.from = new Date(from);
long to = mobileProperty.getLong("to", wifiProperty.getLong("to"));
this.to = new Date(to);
if (wifiProperty.isEmpty()) {
report.remove("wifi");
} else if (wifiProperty.getLong("tx", 0L) + wifiProperty.getLong("rx", 0L) == 0L) {
report.remove("wifi");
} else {
wifiProperty.remove("from");
wifiProperty.remove("to");
}
if (mobileProperty.isEmpty()) {
report.remove("mobile");
} else if (mobileProperty.getLong("tx", 0L) + mobileProperty.getLong("rx", 0L) == 0L) {
report.remove("mobile");
} else {
mobileProperty.remove("from");
mobileProperty.remove("to");
}
if (this.usage.isEmpty()) {
this.usage = null;
}
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public Date getFrom() {
return this.from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return this.to;
}
public void setTo(Date to) {
this.to = to;
}
public DbObject getUsage() {
return this.usage;
}
public long getUsage(String category, String key) {
return this.getUsage().getDbObject(new String[]{category}).getLong(key, 0L);
}
public void setUsage(DbObject usage) {
this.usage = usage;
}
public Date getRecordedAt() {
return this.recordedAt;
}
public void setRecordedAt(Date recordedAt) {
this.recordedAt = recordedAt;
}
public boolean isLaterThan(DataUsage usage) {
return usage.getTo().getTime() < this.getFrom().getTime();
}
public boolean isOverlapped(DataUsage usage) {
return usage.getFrom().getTime() >= this.getTo().getTime() && usage.getTo().getTime() <= this.getTo().getTime();
}
}
@@ -0,0 +1,495 @@
package com.midm.model.device;
import com.google.common.base.Strings;
import com.midm.model.GeneralProfile;
import com.midm.model.battery.Battery;
import com.midm.model.file.OtaFile;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.bson.Document;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
/**
* ======================================================================================
* 核心实体模型:受控终端设备档案 (Device Entity)
* ======================================================================================
*
* <p>【数据建模与 MongoDB 索引架构】
* 1. 业务地位:
* - 作为整个 MDM / IoT 系统的核心资产抽象,代表一台具体的受控智能硬件(PDA / 移动平板 / 车载终端)。
* 2. 【生产级复合索引设计】:
* - `{'profile.hardware_info.serial_no': 1}` (unique = true):
* 以出厂序列号构建唯一业务主键索引,杜绝重复设备接入,提供 O(1) 复杂度的极速检索。
* - `{'deviceGroup.$id': 1}`:
* 按部门/仓库/车辆编队等组织分组高效检索关联设备。
* - `{'owner.$id': 1, 'deviceGroup.$id': 1}`:
* 加速管理员按员工责任人与所属部门进行组合过滤统计。
* 3. 关联映射({@link DBRef}):
* - 关联所属企业员工 (User owner)、商业授权凭据 (DeviceLicense license)、组织分组 (DeviceGroup deviceGroup)。
* 4. 动态属性集(DbObject):
* - `profile`:静态硬件特征(IMEI、MAC、CPU型号、屏幕分辨率、出厂镜像版本);
* - `states`:动态运行快照(当前电量、实时网络类型、内存剩余空间、活跃IP);
* - `installedApps`:端侧已安装的应用清单快照(用于合规检测与版本审计)。
*
* @author MiDM Core Platform Team
*/
@org.springframework.data.mongodb.core.mapping.Document
@CompoundIndexes({@CompoundIndex(
def = "{'deviceGroup.$id':1}"
), @CompoundIndex(
def = "{'profile.hardware_info.serial_no':1}",
unique = true
), @CompoundIndex(
def = "{'owner.$id':1, 'deviceGroup.$id':1}"
)})
public class Device extends GeneralProfile {
/** 所属企业租户主键 UUID(实现多租户严格逻辑隔离) */
private UUID siteUuid;
/** 临时字段:前端传递的目标分组 UUID,不持久化到 MongoDB */
@Transient
private UUID groupUuid;
/** 临时字段:展示给前端的分组全路径(如 "总公司/华东大区/智能物流一号仓") */
@Transient
private String groupPath;
/** 临时字段:归属负责人主键 UUID */
@Transient
private UUID ownerUuid;
/** MongoDB 跨集合引用:设备领用人档案 */
@DBRef
private User owner;
/** MongoDB 跨集合引用:设备绑定的商业 License 授权凭据 */
@DBRef
private DeviceLicense license;
/** MongoDB 跨集合引用:所属层级组织分组 */
@DBRef
private DeviceGroup deviceGroup;
/** 临时字段:设备当前生效的策略清单缓存 */
@Transient
private List deviceProfiles;
/** 许可激活时间点索引 */
@Indexed
private Date licensed;
/** 许可到期时间点索引(用于定时扫描批量过期告警与自动续约) */
@Indexed
private Date licenseExpiry;
/** 临时字段:RSA 鉴权私钥字符串 */
@Transient
private String rsa;
/** 终端动态遥测快照数据字典(电池状态、网络、存储剩余空间等) */
protected DbObject states;
/** 首次入网注册时间戳 */
private Date enrolled;
/** 最近一次活跃心跳上报时间(Check-in,用于离线判定) */
private Date lastCheckedIn;
/** 最近一次 TCP / WebSocket 连接断开时间点 */
private Date lastDisconnected;
/** 终端已安装的应用程序包信息清单快照 */
private List installedApps;
public String getRsa() {
return this.rsa;
}
public void setRsa(String rsa) {
this.rsa = rsa;
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getGroupUuid() {
return this.groupUuid;
}
public String getGroupPath() {
return this.groupPath;
}
public void setGroupPath(String groupPath) {
this.groupPath = groupPath;
}
public User getOwner() {
return this.owner;
}
public void setOwner(User owner) {
this.owner = owner;
if (owner != null) {
this.removeProfile("owner");
}
}
public UUID getOwnerUuid() {
return this.ownerUuid;
}
public void setOwnerUuid(UUID ownerUuid) {
this.ownerUuid = ownerUuid;
}
public boolean hasOwner() {
return this.getOwner() != null;
}
public String getOwnerInfo(String key, String defaultValue) {
if (this.owner == null) {
DbObject owner = this.getProfileCategory(new String[]{"owner"});
return (String)owner.get(key, defaultValue);
} else {
return key.equals("email") ? this.owner.getEmail() : (String)this.owner.getProfile(key, defaultValue);
}
}
public boolean isAssociated() {
return this.getDeviceGroup() != null;
}
public boolean canRegister() {
return !Strings.isNullOrEmpty(this.getSerialNo());
}
public DeviceGroup getDeviceGroup() {
return this.deviceGroup;
}
public void setDeviceGroup(DeviceGroup deviceGroup) {
if (deviceGroup != null && deviceGroup.getSiteUuid().equals(this.getSiteUuid())) {
this.deviceGroup = deviceGroup;
} else {
this.groupUuid = null;
this.deviceGroup = null;
}
}
public DbObject getStates() {
if (this.states == null) {
this.states = new DbObject();
}
return this.states;
}
public void setStates(DbObject states) {
this.states = states;
}
public String getState() {
return this.getStates().getString("state", "unknown");
}
public void setState(String state) {
this.setState("state", state);
}
public boolean isOnline() {
return this.getStates().getBoolean("isOnline", false);
}
public void setOnline(boolean online) {
this.setState("isOnline", online);
}
public boolean isBlocked() {
return this.getStates().containsKey("blocked");
}
public void setState(String key, Object value) {
this.getStates().append(key, value);
}
public void setClientVersion(int version) {
this.getStates().put("clientVersion", version);
}
public int getClientVersion() {
return this.getStates().getInteger("clientVersion", -1);
}
public Battery.BATTERY_CONDITION getBatteryCondition() {
return Battery.BATTERY_CONDITION.forValue(this.getStates().getInteger("batteryCondition", -1));
}
public boolean hasOldClient() {
return this.getClientVersion() < 0;
}
public Date getEnrolled() {
return this.enrolled;
}
public boolean isEnrolled() {
return this.enrolled != null;
}
public void setEnrolled(Date enrolled) {
this.enrolled = enrolled;
this.setState("enrolled");
this.setLicenseExpiry();
}
public boolean isRetired() {
return this.getState().equals("retired");
}
public Date getLastCheckedIn() {
return this.lastCheckedIn;
}
public void setLastCheckedIn() {
this.setLastCheckedIn(new Date());
}
public void setLastCheckedIn(Date lastCheckedIn) {
this.lastCheckedIn = lastCheckedIn;
}
public Date getLastDisconnected() {
return this.lastDisconnected;
}
public void setLastDisconnected() {
this.lastDisconnected = new Date();
}
public void setLastDisconnected(Date disconnected) {
this.lastDisconnected = disconnected;
}
public List getInstalledApps() {
return this.installedApps;
}
public void setInstalledApps(List installedApps) {
this.installedApps = installedApps;
}
public void setDeviceProfiles(List deviceProfiles) {
this.deviceProfiles = deviceProfiles;
}
public String getSerialNo() {
return (String)this.getCategoryProfile("hardware_info", "serial_no");
}
public void setSerialNo(String serialNo) {
this.setProfile("hardware_info", "serial_no", serialNo.trim());
}
public String getModelId() {
return (String)this.getCategoryProfile("hardware_info", "product_id");
}
public String getBuildNo() {
return this.getProfileCategory(new String[]{"software_info"}).getString("build_no");
}
public String getDisplayId() {
return this.getProfileCategory(new String[]{"software_info"}).getString("display_id");
}
public String getProductDisplayId() {
return this.getProfileCategory(new String[]{"software_info"}).getString("product_display_id");
}
public long getBuildDate() {
return this.getProfileCategory(new String[]{"software_info"}).getLong("build_date", -1L);
}
public int getSdkVersion() {
if (this.isEnrolled()) {
int version = this.getProfileCategory(new String[]{"software_info"}).getInteger("sdk_version", -1);
if (version < 0) {
String osVersion = this.getProfileCategory(new String[]{"software_info"}).getString("os_version");
if (!Strings.isNullOrEmpty(osVersion)) {
if (osVersion.startsWith("5.")) {
version = 22;
} else if (osVersion.startsWith("6.")) {
version = 23;
} else if (osVersion.startsWith("7.")) {
version = 25;
} else if (osVersion.startsWith("8.")) {
version = 27;
} else if (osVersion.equals("9")) {
version = 28;
}
}
}
return version;
} else {
return -1;
}
}
public String getCustomerId() {
return (String)this.getCategoryProfile("software_info", "customer_id");
}
public String getRegionImgVersion() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getString("region_version");
}
public String getScriptVersion() {
return (String)this.getCategoryProfile("software_info", "script_version");
}
public long getRegionBuildDate() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getLong("region_build_date");
}
public boolean isGmsAvailable() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getBoolean("gms_available");
}
public String getSkuId() {
String skuId = (String)this.getCategoryProfile("hardware_info", "sku_id");
if (skuId == null) {
if (this.isGmsAvailable()) {
String buildNo = this.getBuildNo();
if (buildNo == null) {
buildNo = this.getDisplayId();
}
if (buildNo != null) {
skuId = buildNo.substring(0, buildNo.indexOf("."));
}
} else {
skuId = OtaFile.parseSkuId(this.getDisplayId());
}
if (skuId == null) {
skuId = OtaFile.parseSkuId(this.getProductDisplayId());
}
if (skuId == null) {
skuId = OtaFile.parseSkuId(this.getBuildNo());
}
if (skuId != null) {
this.setProfile("hardware_info", "sku_id", skuId);
}
}
return skuId;
}
public String getDeviceId() {
return (String)this.getCategoryProfile("hardware_info", "device_id");
}
public String getBuildFingerPrint() {
return (String)this.getCategoryProfile("software_info", "build_fingerprint");
}
public boolean isMobileConnected() {
String type = this.getProfileCategory(new String[]{"network", "active"}).getString("type");
return "MOBILE".equalsIgnoreCase(type);
}
public String getWifiMacAddr() {
return this.getProfileCategory(new String[]{"network", "wifi"}).getString("mac_address");
}
public DeviceLicense getLicense() {
return this.license;
}
public void setLicense(DeviceLicense license) {
this.license = license;
if (license != null) {
this.licensed = new Date();
this.setLicenseExpiry();
}
}
public Date getLicensed() {
return this.licensed;
}
public void setLicensed(Date licensed) {
this.licensed = licensed;
}
private void setLicenseExpiry() {
if (this.hasLicense()) {
if (!this.license.isActivated() && this.isEnrolled()) {
this.license.activate();
}
this.setLicenseExpiry(this.license.getExpiry());
}
}
public Date getLicenseExpiry() {
if (this.licenseExpiry == null && this.hasLicense()) {
this.licenseExpiry = this.license.getExpiry();
}
return this.licenseExpiry;
}
public boolean isLicenseExpired() {
return this.license != null && !this.license.isPerpetual() && this.license.isExpired();
}
public void setLicenseExpiry(Date expiry) {
this.licenseExpiry = expiry;
}
public boolean hasLicense() {
return this.license != null;
}
public boolean isTrial() {
return !this.hasLicense() || this.license.isTrial();
}
public void removeLicense() {
this.setLicense((DeviceLicense)null);
}
public String getPlan() {
return this.license.getPlan();
}
public void reset() {
this.setEnrolled((Date)null);
this.getStates().clear();
}
public Device clone() {
return (Device)McJsonUtils.clone(this);
}
}
@@ -0,0 +1,150 @@
package com.midm.model.device;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class DeviceApps {
@Id
private UUID deviceUuid;
@Transient
private String serialNo;
private String category = "installed";
private List apps;
private Date reported = new Date();
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
public String getSerialNo() {
return this.serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public List getApps() {
return this.apps;
}
public void setApps(List apps) {
this.apps = apps;
}
public AppInfo getClientService() {
return this.getApp("com.mitac.midm.client");
}
public void setClientService(AppInfo appInfo) {
this.setApp(appInfo);
}
public AppInfo getSystemService() {
return this.getApp("com.mitac.midm.system");
}
public void setSystemService(AppInfo appInfo) {
this.setApp(appInfo);
}
public AppInfo getApp(String packageName) {
if (this.apps != null) {
for(AppInfo app : this.apps) {
String appPackage = app.getPackageName();
if (packageName.equals(appPackage)) {
return app;
}
}
}
return null;
}
public void setApp(AppInfo newApp) {
if (newApp != null && !Strings.isNullOrEmpty(newApp.getPackageName())) {
if (this.apps == null) {
this.apps = new ArrayList();
}
this.apps.add(newApp);
}
}
public void fixAbnormal() {
Iterator<AppInfo> it = this.apps.iterator();
while(it.hasNext()) {
AppInfo info = (AppInfo)it.next();
String packageName = info.getPackageName();
String label = info.getLabel();
if (Strings.isNullOrEmpty(packageName)) {
it.remove();
} else if (Strings.isNullOrEmpty(label)) {
info.setLabel(packageName);
}
}
}
public Date getReported() {
return this.reported;
}
public void setReported(Date reported) {
this.reported = reported;
}
public boolean isAppInstalled(int deviceSdk, String packageName, long versionCode, int minSdk) {
if (minSdk != -1 && deviceSdk < minSdk) {
return true;
} else {
AppInfo appInfo = this.getApp(packageName);
return appInfo != null ? (long)appInfo.getVersionCode() >= versionCode : false;
}
}
public boolean equals(Object obj) {
List<AppInfo> newApps = null;
if (obj instanceof DeviceApps) {
DeviceApps deviceApps = (DeviceApps)obj;
newApps = deviceApps.getApps();
if (this.apps != null && newApps != null && this.apps.size() == newApps.size()) {
if (this.apps.isEmpty()) {
return true;
}
for(AppInfo newAppInfo : newApps) {
AppInfo curInfo = this.getApp(newAppInfo.getPackageName());
if (curInfo == null || newAppInfo.getVersionCode() != curInfo.getVersionCode()) {
return false;
}
}
return true;
}
}
return false;
}
}
@@ -0,0 +1,91 @@
package com.midm.model.device;
import com.midm.model.GeneralProfile;
import java.util.List;
import java.util.UUID;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class DeviceGroup extends GeneralProfile implements Comparable {
private UUID siteUuid;
private UUID parentUuid;
private Integer order;
@Transient
private Integer deviceNumbers;
private List children;
public DeviceGroup() {
this.deviceNumbers = 0;
}
public DeviceGroup(UUID uuid) {
this.uuid = uuid;
}
public DeviceGroup(UUID siteUuid, UUID parentUuid, String name) {
this.init();
this.siteUuid = siteUuid;
this.parentUuid = parentUuid;
this.setName(name);
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getParentUuid() {
return this.parentUuid;
}
public void setParentUuid(UUID parentUuid) {
this.parentUuid = parentUuid;
}
public Integer getOrder() {
return this.order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Integer getDeviceNumbers() {
return this.deviceNumbers;
}
public void setDeviceNumbers(Integer numbers) {
this.deviceNumbers = numbers == null ? 0 : numbers;
}
public List getChildren() {
return this.children;
}
public void setChildren(List children) {
this.children = children;
}
public boolean equals(UUID uuid) {
return this.uuid != null && this.uuid.equals(uuid);
}
public int compareTo(Object target) {
UUID targetUuid = null;
if (target instanceof UUID) {
targetUuid = (UUID)target;
} else if (target instanceof DeviceGroup) {
targetUuid = ((DeviceGroup)target).getUuid();
}
if (targetUuid == null) {
return this.uuid == null ? 0 : 1;
} else {
return this.uuid == null ? -1 : this.uuid.compareTo(targetUuid);
}
}
}
@@ -0,0 +1,48 @@
package com.midm.model.device;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class DeviceKey {
@Id
private UUID uuid;
@Indexed
private String deviceSerial;
private String rsa;
private Date created;
public DeviceKey() {
this((String)null, (String)null);
}
public DeviceKey(String deviceSerial, String rsa) {
this.uuid = UUID.randomUUID();
this.created = new Date();
this.deviceSerial = deviceSerial;
this.rsa = rsa;
}
public String getDeviceSerial() {
return this.deviceSerial;
}
public void setDeviceSerial(String deviceSerial) {
this.deviceSerial = deviceSerial;
}
public String getRsa() {
return this.rsa;
}
public void setRsa(String rsa) {
this.rsa = rsa;
}
public Date getCreated() {
return this.created;
}
}
@@ -0,0 +1,427 @@
package com.midm.model.device;
import com.midm.model.org.Site;
import com.midm.model.org.SiteLicense;
import com.midm.model.system.LicenseModel;
import com.mitac.cell.utils.McDateTimeUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndexes({@CompoundIndex(
def = "{'site.$id': 1}"
), @CompoundIndex(
def = "{'siteLicense.$id': 1}"
), @CompoundIndex(
def = "{'licenseModel.$id': 1}"
), @CompoundIndex(
def = "{'plan': 1, 'site.$id': 1, 'expiry': 1}"
), @CompoundIndex(
def = "{'plan': 1, 'licenseModel.$id': 1, 'site.$id': 1, 'expiry': 1}"
), @CompoundIndex(
def = "{'plan': 1, 'childSite.$id': 1, 'licenseModel.$id': 1, 'site.$id': 1, 'expiry': 1}"
), @CompoundIndex(
def = "{'plan': 1,\t'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}"
), @CompoundIndex(
def = "{'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}"
)})
public class DeviceLicense {
@Id
private UUID uuid;
@Indexed
private UUID deviceUuid;
@Indexed
private String deviceSerial;
@DBRef
private SiteLicense siteLicense;
@DBRef
private SiteLicense childSiteLicense;
@DBRef
private Site site;
@DBRef
private Site childSite;
@DBRef
private LicenseModel licenseModel;
private String plan;
private boolean autoRenew;
private boolean renewToSameModel;
private int activationCount;
@Indexed
private Date activatedAt;
@Indexed
private Date expiry;
private List reactivated;
private Date created;
public DeviceLicense() {
this.plan = "standard";
this.autoRenew = false;
this.renewToSameModel = false;
this.uuid = UUID.randomUUID();
this.created = new Date();
}
public DeviceLicense(SiteLicense license) {
this((Device)null, (SiteLicense)license);
}
public DeviceLicense(SiteLicense license, String plan) {
this((Device)null, (SiteLicense)license);
this.setPlan(plan);
}
public DeviceLicense(Device device) {
this();
this.setDevice(device);
}
public DeviceLicense(Device device, SiteLicense license) {
this();
this.setSiteLicense(license);
this.setDevice(device);
}
public DeviceLicense(Device device, LicenseModel licenseModel) {
this();
this.setLicenseModel(licenseModel);
this.setDevice(device);
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public SiteLicense getSiteLicense() {
return this.siteLicense;
}
public void setSiteLicense(SiteLicense license) {
this.siteLicense = license;
if (license != null) {
this.setSite(license.getSite());
this.setLicenseModel(license.getLicenseModel());
} else {
this.setLicenseModel((LicenseModel)null);
}
}
public SiteLicense getChildSiteLicense() {
return this.childSiteLicense;
}
public void setChildSiteLicense(SiteLicense license) {
this.childSiteLicense = license;
}
public boolean isLite() {
return this.site.isLite() || this.plan.equals("lite");
}
public Site getSite() {
return this.site;
}
public void setSite(Site site) {
if (site == null) {
this.site = this.childSite = null;
} else if (site.isChild()) {
this.setSite(site.getReseller());
this.setChildSite(site);
} else {
this.site = site;
}
}
public Site getChildSite() {
return this.childSite;
}
public void setChildSite(Site child) {
this.childSite = child;
}
public boolean hasLicenseModel() {
return this.getLicenseModel() != null;
}
public LicenseModel getLicenseModel() {
return this.licenseModel;
}
public void setLicenseModel(LicenseModel licenseModel) {
this.setLicenseModel(licenseModel, true);
}
public void setLicenseModel(LicenseModel licenseModel, boolean setExpiry) {
this.licenseModel = licenseModel;
if (licenseModel != null && setExpiry) {
this.expiry = this.licenseModel.getFreshExpiry(new Date());
}
}
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
public boolean setDevice(Device device) {
if (this.isExceedActivationCount() && this.beforeExpiry()) {
return false;
} else if (device == null) {
if (this.isTrial()) {
this.expire();
} else {
this.setDeviceUuid((UUID)null);
this.setDeviceSerial((String)null);
this.setAutoRenew(false);
this.setRenewToSameModel(false);
if (this.isExceedActivationCount()) {
this.expire();
}
}
return true;
} else {
this.setDeviceSerial(device.getSerialNo());
this.setDeviceUuid(device.getUuid());
if (device.isEnrolled()) {
if (this.isActivated()) {
++this.activationCount;
if (this.isPerpetual()) {
Date nextExpiry = this.licenseModel.getNextExpiry(new Date());
if (this.expiry.before(nextExpiry)) {
this.expiry = nextExpiry;
}
}
} else {
this.activate();
}
}
return true;
}
}
public String getDeviceSerial() {
return this.deviceSerial;
}
public void setDeviceSerial(String serialNo) {
this.deviceSerial = serialNo;
}
public String getPlan() {
return this.plan;
}
public void setPlan(String plan) {
this.plan = plan;
}
public boolean isAutoRenew() {
return this.autoRenew;
}
public void setAutoRenew(boolean autoRenew) {
this.autoRenew = autoRenew;
}
public boolean isRenewToSameModel() {
return this.renewToSameModel;
}
public void setRenewToSameModel(boolean renewToSameModel) {
this.renewToSameModel = renewToSameModel;
}
public int getActivationCount() {
return this.activationCount;
}
public void setActivationCount(int count) {
if (count < 0) {
count = 0;
}
this.activationCount = count;
if (this.activationCount == 0) {
this.setActivatedAt((Date)null);
}
}
public void resetActivationCount() {
if (this.isTrial()) {
this.setActivationCount(0);
this.setActivatedAt((Date)null);
} else {
this.setActivationCount(--this.activationCount);
}
}
public boolean exceedActivationCount(int maxActivationCount) {
return this.activationCount > maxActivationCount;
}
public boolean isActive() {
return this.activatedAt == null;
}
public boolean isActivated() {
return this.activatedAt != null;
}
public boolean isExpired() {
return !this.beforeExpiry();
}
public boolean canExtend() {
if (!this.isPerpetual()) {
return false;
} else {
List<Date> reactivated = this.getReactivated();
if ((reactivated == null || reactivated.size() != 2) && (!this.isExceedActivationCount() || this.getDeviceUuid() != null)) {
DateTime expiry = new DateTime(this.getExpiry());
DateTime now = DateTime.now();
return now.plusDays(45).isAfter(expiry) && expiry.plusDays(14).isAfter(now);
} else {
return false;
}
}
}
public Date getActivatedAt() {
return this.activatedAt;
}
public Boolean activate() {
return this.isActivated() ? true : this.setActivatedAt(new Date());
}
public Boolean setActivatedAt(Date activatedAt) {
if (!this.isActivated()) {
this.activatedAt = activatedAt;
this.expiry = this.licenseModel.getActivatedExpiry(activatedAt);
if (activatedAt != null) {
++this.activationCount;
}
return true;
} else if (this.isActivated() && this.activationCount < this.licenseModel.getMaxActivation()) {
if (activatedAt != null) {
++this.activationCount;
}
return true;
} else {
return false;
}
}
public void reset() {
this.setDevice((Device)null);
}
public Date getExpiry() {
return this.expiry;
}
public boolean beforeExpiry() {
return this.expiry != null && this.expiry.after(new Date());
}
public void setExpiry(Date expiryDate) {
this.expiry = expiryDate;
}
public void extendExpiryDays(int days) {
this.setExpiry((new DateTime()).plusDays(days).toDate());
}
public void expire() {
this.setExpiry(new Date());
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public boolean isPerpetual() {
return this.licenseModel != null && this.licenseModel.isPerpetual();
}
public boolean isTrial() {
return this.siteLicense == null || this.licenseModel == null || this.licenseModel.isTrial();
}
public boolean isExceedActivationCount() {
int maxCount = this.licenseModel == null ? 2 : this.licenseModel.getMaxActivation();
return maxCount > 0 && maxCount <= this.activationCount;
}
public boolean isValid() {
return this.isPerpetual() ? true : (new Date()).before(this.expiry);
}
public boolean isSameLicenseModel(UUID licenseModelUuid) {
return this.licenseModel != null && this.licenseModel.getUuid().equals(licenseModelUuid);
}
public int getRemainingDays() {
return this.expiry.before(new Date()) ? 0 : McDateTimeUtils.daysBetween(new DateTime(this.expiry), DateTime.now());
}
public List getReactivated() {
return this.reactivated;
}
public void setReactivated(List reactivated) {
this.reactivated = reactivated;
}
public boolean reactivate() {
if (this.isPerpetual()) {
if (this.reactivated == null) {
this.reactivated = new ArrayList();
}
if (this.reactivated.size() < 2) {
LocalDate today = LocalDate.now();
this.reactivated.add(today.toDate());
this.setExpiry((new DateTime(this.getExpiry())).plusYears(1).toDate());
return true;
}
}
return false;
}
public String getPo() {
return this.childSiteLicense != null ? this.childSiteLicense.getPo() : (this.siteLicense != null ? this.siteLicense.getPo() : null);
}
}
@@ -0,0 +1,73 @@
package com.midm.model.device;
import com.midm.model.org.User;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class DeviceNote {
@Id
private UUID uuid;
private UUID deviceUuid;
private UUID writerUuid;
@Transient
private User writer;
private String note;
private Date registeredAt;
public void init() {
this.setUuid(UUID.randomUUID());
this.setRegisteredAt(new Date());
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
public UUID getWriterUuid() {
return this.writerUuid;
}
public void setWriterUuid(UUID writerUuid) {
this.writerUuid = writerUuid;
}
public User getWriter() {
return this.writer;
}
public void setWriter(User writer) {
this.writer = writer;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
public Date getRegisteredAt() {
return this.registeredAt;
}
public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt;
}
}
@@ -0,0 +1,349 @@
package com.midm.model.device;
import com.google.gson.annotations.Expose;
import com.midm.model.GeneralProfile;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndex(
def = "{'deviceProfileGroup.uuid': 1}"
)
public class DeviceProfile extends GeneralProfile {
@Indexed
private UUID siteUuid;
@DBRef
private DeviceProfileGroup deviceProfileGroup;
private UUID writerUuid;
private boolean isGlobal;
private DbObject status;
private ProfileApps apps;
private List otas;
private DbObject files;
private ProfileScope scope;
private List sequence;
@Transient
private DbObject progress;
@Transient
private DbObject reference;
@Transient
private UUID groupUuid;
@Transient
private User writer;
@Expose(
serialize = false
)
@Transient
private boolean needOldFormat = false;
public UUID getSiteUuid() {
return this.siteUuid;
}
public boolean isGlobal() {
return this.isGlobal;
}
public void setIsGlobal(boolean isGlobal) {
this.isGlobal = isGlobal;
}
public UUID getGroupUuid() {
return this.groupUuid;
}
public void setGroupUuid(UUID groupUuid) {
this.groupUuid = groupUuid;
}
public DeviceProfileGroup getDeviceProfileGroup() {
return this.deviceProfileGroup;
}
public void setDeviceProfileGroup(DeviceProfileGroup deviceProfileGroup) {
this.deviceProfileGroup = deviceProfileGroup;
if (deviceProfileGroup == null) {
this.groupUuid = null;
}
}
public Set getFileUUids() {
Set<UUID> pushUuids = new HashSet();
if (this.files != null && !this.files.isEmpty() && this.files.containsKey("push")) {
List<DbObject> pushes = this.files.getList("push", DbObject.class);
pushes.forEach((pushItem) -> {
List<Object> sources = pushItem.getList("sources", Object.class);
sources.forEach((source) -> {
if (source instanceof UUID) {
pushUuids.add((UUID)source);
} else if (source instanceof String) {
pushUuids.add(UUID.fromString((String)source));
}
});
});
}
return pushUuids;
}
public String applyOrder() {
return this.getProfile().getString("applyOrder", "none");
}
public List getSequence() {
return this.sequence;
}
public boolean hasSequence() {
return this.sequence != null && !this.sequence.isEmpty();
}
public void setSequence(List sequence) {
this.sequence = sequence;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getWriterUuid() {
return this.writerUuid;
}
public void setWriterUuid(UUID writerUuid) {
this.writerUuid = writerUuid;
}
public DbObject getStatus() {
return this.status;
}
public void setStatus(DbObject status) {
this.status = status;
}
public ProfileScope getScope() {
return this.scope;
}
public boolean hasScope() {
return this.scope != null && this.scope.hasScoped();
}
public boolean hasScopeDeviceGroups() {
return this.scope != null && this.scope.getGroup() != null && !this.scope.getGroup().isEmpty();
}
public Set getScopedDeviceGroups() {
return this.scope == null ? null : this.scope.getGroup();
}
public Set getScopedDevice() {
return this.scope == null ? null : this.scope.getDevice();
}
public void setScope(ProfileScope scope) {
this.scope = scope;
}
public User getWriter() {
return this.writer;
}
public void setWriter(User writer) {
this.writer = writer;
}
public void initApps() {
if (this.apps != null) {
this.apps.initInstallApp();
this.apps.setInstall(this.apps.getInstallApp());
}
}
public ProfileApps getApps() {
return this.apps;
}
public List getInstallApps() {
if (this.apps == null) {
this.initApps();
}
return this.apps == null ? null : this.apps.getInstallApp();
}
public List getInstallUuids() {
if (this.apps == null) {
this.initApps();
}
return this.apps != null ? this.apps.getInstallUuids() : null;
}
public ProfileApps.InstallApp getInstallApp(String packageName) {
if (this.apps == null) {
this.initApps();
}
return this.apps != null ? this.apps.getInstallApp(packageName) : null;
}
public void setApps(ProfileApps apps) {
this.apps = apps;
}
public boolean needOldFormat() {
return this.needOldFormat;
}
public void setNeedOldFormat(boolean need) {
this.needOldFormat = need;
}
public void setToOldFormat() {
if (this.apps != null) {
this.apps.setToOldFormat();
}
}
public List getWhiteListPackages() {
return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null;
}
public List getBlackListPackages() {
return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null;
}
public List getOtas() {
return this.otas;
}
public void setOtas(List otas) {
this.otas = otas;
}
public boolean checkBuildDate() {
return this.getSettingAsBoolean("otas", "checkBuildDate", false);
}
public DbObject getFiles() {
return this.files;
}
public void setFiles(DbObject files) {
this.files = files;
}
public DbObject getProgress() {
return this.progress;
}
public void setProgress(DbObject progress) {
this.progress = progress;
}
public DbObject getReference() {
return this.reference;
}
public void setReference(DbObject reference) {
this.reference = reference;
}
public void setReference(String key, Object data) {
if (data == null) {
if (this.reference != null) {
this.reference.remove(key);
}
} else if (this.reference == null) {
this.reference = new DbObject(key, data);
} else {
this.reference.put(key, data);
}
}
public void unsetDateTimeSettings() {
DbObject settings = this.getSettingsCategory(new String[]{"system", "dateTime"});
if (settings != null) {
if (settings.containsKey("hourFormat")) {
settings.remove("hourFormat");
}
if (settings.size() > 0) {
this.setSetting("system", "dateTime", settings);
} else {
this.setSetting("system", "dateTime", (Object)null);
}
}
}
public void convertCustomSettingsForDevice() {
String[] categories = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"};
for(String category : categories) {
Object settingValue = this.getSetting(category);
if (settingValue instanceof List) {
List<? extends Map<String, ?>> settings = (List)this.getSetting(category);
if (settings != null && !settings.isEmpty()) {
DbObject newSettings = new DbObject();
settings.forEach((item) -> newSettings.append((String)item.get("key"), item.get("value")));
this.setSetting(category, newSettings);
}
} else if (settingValue instanceof DbObject) {
this.setSetting(category, (UUID)null);
}
}
if (this.getSettings().containsKey("midm")) {
boolean reboot = this.getSettingsCategory(new String[]{"midm"}).getBoolean("reboot", true);
DbObject systemSettings = this.getSettingsCategory(new String[]{"systemSettings"});
if (systemSettings == null) {
systemSettings = new DbObject();
}
systemSettings.put("midmclient.reboot", Character.valueOf((char)(reboot ? '1' : '0')));
} else if (this.settings.containsKey("otas") && (this.otas == null || this.otas.isEmpty())) {
this.settings.remove("otas");
this.otas = null;
}
}
public boolean removeIfNoScope() {
return this.getProfile().getBoolean("removeIfNoScope", false);
}
public boolean unscopeIfApplied() {
return this.getProfile().getBoolean("unscopeIfApplied", false);
}
public void minify() {
super.minify();
this.deviceProfileGroup = null;
this.scope = null;
this.writerUuid = null;
this.writer = null;
}
public DeviceProfile clone() {
return (DeviceProfile)McJsonUtils.clone(this);
}
}
@@ -0,0 +1,57 @@
package com.midm.model.device;
import com.midm.model.GeneralProfile;
import java.util.List;
import java.util.UUID;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class DeviceProfileGroup extends GeneralProfile {
private UUID siteUuid;
private UUID parentUuid;
private Integer order;
@Transient
private Long deviceProfileNumbers;
private List children;
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getParentUuid() {
return this.parentUuid;
}
public void setParentUuid(UUID parentUuid) {
this.parentUuid = parentUuid;
}
public Integer getOrder() {
return this.order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Long getDeviceProfileNumbers() {
return this.deviceProfileNumbers;
}
public void setDeviceProfileNumbers(Long numbers) {
this.deviceProfileNumbers = numbers;
}
public List getChildren() {
return this.children;
}
public void setChildren(List children) {
this.children = children;
}
}
@@ -0,0 +1,155 @@
package com.midm.model.device;
import com.mitac.cell.db.DbObject;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndexes({@CompoundIndex(
def = "{'_id.deviceUuid': 1}"
), @CompoundIndex(
def = "{'_id.profileUuid': 1}"
)})
public class DeviceProfileState {
public static final String STATE_IN_PROGRESS = "in_progress";
public static final String STATE_DONE = "done";
public static final String STATE_UNKNWON = "unknown";
@Id
private Scoped scoped;
private long updated = -1L;
@Indexed
private String state = "unknown";
private String applyFirstState = "unknown";
@Indexed
private long applied;
@Transient
private DeviceReport report;
public DeviceProfileState() {
}
public DeviceProfileState(Device device, DeviceProfile profile) {
this.scoped = new Scoped(profile.getUuid(), device.getUuid());
this.updated = profile.getUpdated().getTime();
this.applied = (new Date()).getTime();
}
public DeviceProfileState(DeviceReport report) {
this.setReport(report);
}
public Scoped getScoped() {
return this.scoped;
}
public void setScoped(Scoped scoped) {
this.scoped = scoped;
}
public UUID getProfileUuid() {
return this.getScoped().getProfileUuid();
}
public UUID getDeviceUuid() {
return this.getScoped().getDeviceUuid();
}
public long getUpdated() {
return this.updated;
}
public void setUpdated(long updated) {
this.updated = updated;
}
public String getState() {
return this.state;
}
public boolean isDone() {
return this.state == null || this.state.equals("done");
}
public void setState(String state) {
this.state = state;
}
public String getApplyFirstState() {
return this.applyFirstState;
}
public boolean isApplyFirstDone() {
return this.applyFirstState != null && this.applyFirstState.equals("done");
}
public void setApplyFirstState(String applyFirstState) {
this.applyFirstState = applyFirstState;
}
public long getApplied() {
return this.applied;
}
public void setApplied(long applied) {
this.applied = applied;
this.setState("done");
}
public void setApplied(long applied, String state) {
this.state = state;
this.applied = applied;
}
public void setApplied() {
this.applied = (new Date()).getTime();
}
public DeviceReport getReport() {
return this.report;
}
public void setReport(DeviceReport report) {
this.report = report;
DbObject profile = report.getProperties().getDbObject(new String[]{"deviceProfile"});
this.scoped = new Scoped(profile.getUuid("uuid"), report.getDeviceUuid());
this.updated = profile.getLong("updated", -1L);
this.applied = profile.getLong("applied", -1L);
this.setState("done");
}
public static class Scoped implements Serializable {
private UUID profileUuid;
private UUID deviceUuid;
public Scoped() {
}
public Scoped(UUID profileUuid, UUID deviceUuid) {
this.profileUuid = profileUuid;
this.deviceUuid = deviceUuid;
}
public UUID getProfileUuid() {
return this.profileUuid;
}
public void setProfileUuid(UUID profileUuid) {
this.profileUuid = profileUuid;
}
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
}
}
@@ -0,0 +1,136 @@
package com.midm.model.device;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* ======================================================================================
* IoT 设备时序遥测上报数据模型 (DeviceReport)
* ======================================================================================
*
* <p>【时序遥测存储与复合索引优化】
* 1. 业务场景:
* - 采集移动受控设备的动态遥测快照(GPS地理坐标、传感器数值、网络质量、策略生效版本等)。
* 2. 【高并发时序复合索引】:
* - `{'deviceUuid': 1, 'properties.location.time': -1}`:
* 按设备维度按时间倒序快速检索设备的历史运动轨迹,支撑地理围栏(Geo-fencing)与电子地图回放;
* - `{'properties.deviceProfile.uuid': 1, 'properties.deviceProfile.updated': 1}`:
* 用于统计各策略配置(DeviceProfile)在设备上的下发与部署成功率。
*
* @author MiDM Core Platform Team
*/
@Document
@CompoundIndexes({@CompoundIndex(
def = "{'properties.deviceProfile.uuid':1, 'properties.deviceProfile.updated':1}"
), @CompoundIndex(
def = "{'deviceUuid':1, 'properties.location.time': -1}"
)})
public class DeviceReport {
/** 报告记录全局主键 UUID */
@Id
private UUID uuid;
/** 关联的目标受控硬件主键 UUID */
private UUID deviceUuid;
/** 临时字段:设备序列号 */
@Transient
private String serialNo;
/** 动态遥测属性字典(包含 GPS 坐标:properties.location.latitude / longitude 等) */
private DbObject properties;
/** 终端边缘侧本地采样并生成该报文的时间戳 */
private Date reportedAt;
/** 云端服务端持久化写入数据库的系统时间戳 */
private Date recordedAt;
public DeviceReport() {
this.setRecordedAt();
}
public void init() {
this.setUuid(UUID.randomUUID());
this.setReportedAt(new Date());
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getDeviceUuid() {
return this.deviceUuid;
}
public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid;
}
public String getSerialNo() {
return this.serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public boolean hasProperties() {
return this.properties != null && !this.properties.isEmpty();
}
public DbObject getProperties() {
if (this.properties == null) {
this.properties = new DbObject();
}
return this.properties;
}
public void setProperties(DbObject properties) {
this.properties = properties;
}
public Date getReportedAt() {
return this.reportedAt;
}
public void setReportedAt(Date reportedAt) {
this.reportedAt = reportedAt;
}
public Date getRecordedAt() {
return this.recordedAt;
}
public void setRecordedAt(Date recordedAt) {
this.recordedAt = recordedAt;
}
public void setRecordedAt() {
this.recordedAt = new Date();
}
public void setProperty(String key, Object val) {
this.getProperties().append(key, val);
}
public Object getProperty(String key) {
return this.getProperties().get(key);
}
public String toString() {
return McJsonUtils.toJson(this);
}
}
@@ -0,0 +1,289 @@
package com.midm.model.device;
import com.google.common.reflect.TypeToken;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.midm.model.file.AppFile;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Field;
public class ProfileApps {
private List install;
@Transient
@Expose(
serialize = false
)
private List installApp;
private List uninstall;
@SerializedName("add_appwidget")
@Field("add_appwidget")
private List appWidget;
private List widget;
@SerializedName("grant_all")
@Field("grant_all")
private List grantAll;
private List disabled;
@SerializedName("wifi_only")
@Field("wifi_only")
private List wifiOnly;
@SerializedName("white_list")
@Field("white_list")
private List whiteList;
@SerializedName("black_list")
@Field("black_list")
private List blackList;
public List getInstall() {
return this.install;
}
public void setInstall(List install) {
this.install = install;
}
public void setToOldFormat() {
this.install = this.getInstallUuids();
}
public List getInstallApp() {
if (this.installApp == null && this.install != null) {
this.initInstallApp();
}
return this.installApp;
}
public void initInstallApp() {
if (this.install != null && !this.install.isEmpty()) {
if (this.install.get(0) instanceof InstallApp) {
this.installApp = this.install;
} else {
this.installApp = (List)McJsonUtils.toObject(McJsonUtils.toJsonElement(this.install), (new TypeToken() {
}).getType());
this.install = this.installApp;
}
}
}
public void setInstallApp(List installApp) {
this.installApp = installApp;
}
public boolean hasInstallApps() {
this.getInstallApp();
return this.installApp != null && !this.installApp.isEmpty();
}
public InstallApp getInstallApp(String packageName) {
if (!this.hasInstallApps()) {
return null;
} else {
for(InstallApp app : this.installApp) {
if (packageName.equals(app.getPackageName())) {
return app;
}
}
return null;
}
}
public boolean removeInstallApp(UUID appUuid) {
if (this.hasInstallApps()) {
Iterator<InstallApp> it = this.installApp.iterator();
while(it.hasNext()) {
if (((InstallApp)it.next()).uuid.equals(appUuid)) {
it.remove();
return true;
}
}
}
return false;
}
public List getInstallUuids() {
return this.installApp != null ? (List)this.installApp.stream().map((app) -> app.getUuid()).collect(Collectors.toList()) : null;
}
public List getUninstall() {
return this.toDbList(this.uninstall);
}
public void setUninstall(List uninstall) {
this.uninstall = uninstall;
}
public List getAppWidget() {
return this.appWidget;
}
public void setAppWidget(List addAppWidget) {
this.appWidget = addAppWidget;
}
public List getWidget() {
return this.widget;
}
public void setWidget(List widget) {
this.widget = widget;
}
public List getGrantAll() {
return this.toDbList(this.grantAll);
}
public void setGrantAll(List grantAll) {
this.grantAll = grantAll;
}
public List getDisabled() {
return this.toDbList(this.disabled);
}
public void setDisabled(List disabled) {
this.disabled = disabled;
}
public List getWifiOnly() {
return this.toDbList(this.wifiOnly);
}
public void setWifiOnly(List wifiOnly) {
this.wifiOnly = wifiOnly;
}
public List getWhiteList() {
return this.toDbList(this.whiteList);
}
public void setWhiteList(List whiteList) {
this.whiteList = whiteList;
}
public List getBlackList() {
return this.toDbList(this.blackList);
}
public void setBlackList(List blackList) {
this.blackList = blackList;
}
public List getPackageList(List apps) {
return apps != null ? (List)apps.stream().map((app) -> app.getString("package")).collect(Collectors.toList()) : null;
}
public boolean isEmpty() {
return (this.install == null || this.install.isEmpty()) && (this.uninstall == null || this.uninstall.isEmpty()) && (this.appWidget == null || this.appWidget.isEmpty()) && (this.widget == null || this.widget.isEmpty()) && (this.grantAll == null || this.grantAll.isEmpty()) && (this.disabled == null || this.disabled.isEmpty()) && (this.wifiOnly == null || this.wifiOnly.isEmpty()) && (this.whiteList == null || this.whiteList.isEmpty()) && (this.blackList == null || this.blackList.isEmpty());
}
private List toDbList(List list) {
if (list != null && !list.isEmpty()) {
List<DbObject> dbList = new ArrayList();
list.forEach((item) -> {
if (item instanceof DbObject) {
dbList.add((DbObject)item);
} else if (item instanceof Map) {
dbList.add(new DbObject((Map)item));
}
});
return dbList;
} else {
return null;
}
}
public static class InstallApp {
private UUID uuid;
private String packageName;
@SerializedName("silent_install")
@Field("silent_install")
private Boolean silentInstall = true;
@SerializedName("grant_all")
@Field("grant_all")
private Boolean grantAll = false;
@SerializedName("starts_on_update")
@Field("starts_on_update")
private Boolean startsOnUpdate = false;
@SerializedName("reboots_on_update")
@Field("reboots_on_update")
private Boolean rebootsOnUpdate = false;
public InstallApp() {
}
public InstallApp(AppFile appFile) {
this.uuid = appFile.getFileUuid();
this.packageName = appFile.getPackageName();
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public Boolean getSilentInstall() {
return this.silentInstall;
}
public void setSilentInstall(Boolean silentInstall) {
this.silentInstall = silentInstall;
}
public Boolean getGrantAll() {
return this.grantAll;
}
public void setGrantAll(Boolean grantAll) {
this.grantAll = grantAll;
}
public Boolean getStartsOnUpdate() {
return this.startsOnUpdate;
}
public void setStartsOnUpdate(Boolean startsOnUpdate) {
this.startsOnUpdate = startsOnUpdate;
}
public Boolean getRebootsOnUpdate() {
return this.rebootsOnUpdate;
}
public void setRebootsOnUpdate(Boolean rebootsOnUpdate) {
this.rebootsOnUpdate = rebootsOnUpdate;
}
public boolean equals(Object obj) {
if (!(obj instanceof InstallApp)) {
return false;
} else {
InstallApp installApp = (InstallApp)obj;
return this.uuid.equals(installApp.uuid) && this.packageName.equals(installApp.packageName) && this.silentInstall == installApp.silentInstall && this.grantAll == installApp.grantAll && this.startsOnUpdate == installApp.startsOnUpdate && this.rebootsOnUpdate == installApp.rebootsOnUpdate;
}
}
}
}
@@ -0,0 +1,69 @@
package com.midm.model.device;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class ProfileScope {
Set group;
Set device;
Set userGroup;
public Set getGroup() {
return this.group;
}
public void setGroup(Set group) {
this.group = group;
}
public void addGroup(UUID groupUuid) {
if (this.group == null) {
this.group = new HashSet();
this.group.add(groupUuid);
}
}
public void removeGroup(UUID groupUuid) {
if (this.group != null) {
this.group.remove(groupUuid);
}
}
public Set getDevice() {
return this.device;
}
public void setDevice(Set device) {
this.device = device;
}
public void addDevice(String serialNo) {
if (this.device == null) {
this.device = new HashSet();
this.device.add(serialNo);
}
}
public void removeDevice(String serialNo) {
if (this.device != null) {
this.device.remove(serialNo);
}
}
public Set getUserGroup() {
return this.userGroup;
}
public void setUserGroup(Set userGroup) {
this.userGroup = userGroup;
}
public boolean hasScoped() {
return this.group != null && !this.group.isEmpty() || this.device != null && !this.device.isEmpty() || this.userGroup != null && !this.userGroup.isEmpty();
}
}
@@ -0,0 +1,164 @@
package com.midm.model.device;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import org.joda.time.LocalDateTime;
public class ReconnectMonitor {
private static final int BLOCKING_HOURS = 12;
private static final int RECONNECT_FOR = 10;
private Device device;
private Date startedAt;
private long prevMins;
private int count;
private int total;
private Date blockedAt;
private Date unblockAt;
private Timer unblockTimer;
private OnAbusedListener listener;
public ReconnectMonitor(Device device, OnAbusedListener listener) {
this.device = device;
this.listener = listener;
this.init();
}
private void init() {
this.startedAt = new Date();
this.blockedAt = null;
this.unblockAt = null;
this.prevMins = this.getCurMins();
this.total = this.count = 1;
}
public Device getDevice() {
return this.device;
}
public UUID getDeviceUuid() {
return this.device.getUuid();
}
public Date getStartedAt() {
return this.startedAt;
}
public Date getBlockedAt() {
return this.blockedAt;
}
public Date getUnblockAt() {
return this.unblockAt;
}
public int getCount() {
return this.count;
}
public int getTotal() {
return this.total;
}
public void connected() {
long curMins = this.getCurMins();
long gap = curMins - this.prevMins;
if (gap <= 1L) {
++this.total;
if (gap == 1L) {
++this.count;
this.prevMins = curMins;
if (this.count >= 10) {
this.blockedAt = new Date();
this.onAbused();
}
}
} else {
this.init();
}
}
public boolean isBlocked() {
return this.blockedAt != null;
}
public void block() {
this.blockedAt = new Date();
this.unblockAt = (new LocalDateTime(this.blockedAt)).plusHours(12).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).toDate();
this.startUnblockTimer();
}
public void block(Device device) {
if (device.isBlocked()) {
DbObject blockedState = device.getStates().getDbObject(new String[]{"blocked"});
this.blockedAt = blockedState.getDate("from");
this.unblockAt = blockedState.getDate("to");
if (this.unblockAt.getTime() < (new Date()).getTime()) {
this.unblock((User)null);
} else {
this.startUnblockTimer();
}
} else {
this.block();
}
}
private void startUnblockTimer() {
this.stopUnblockTimer();
String var10003 = this.device.getUuid().toString();
this.unblockTimer = new Timer(var10003 + (new Date()).getTime());
this.unblockTimer.schedule(new TimerTask() {
public void run() {
ReconnectMonitor.this.unblock((User)null);
}
}, this.unblockAt);
}
private void stopUnblockTimer() {
if (this.unblockTimer != null) {
try {
this.unblockTimer.cancel();
this.unblockTimer.purge();
this.unblockTimer = null;
} catch (Exception var2) {
}
}
}
public void unblock(User user) {
this.stopUnblockTimer();
this.startedAt = null;
this.blockedAt = null;
this.unblockAt = null;
this.prevMins = 0L;
this.total = this.count = 0;
if (this.listener != null) {
this.listener.onUnblocked(this, user);
}
}
private void onAbused() {
this.block();
if (this.listener != null) {
this.listener.onAbused(this);
}
}
private long getCurMins() {
return (new Date()).getTime() / 60000L;
}
public interface OnAbusedListener {
void onAbused(ReconnectMonitor monitor);
void onUnblocked(ReconnectMonitor monitor, User user);
}
}
@@ -0,0 +1,229 @@
package com.midm.model.file;
import com.google.api.client.util.Strings;
import com.google.gson.annotations.Expose;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.io.McApkFile;
import com.mitac.cell.io.McFile;
import java.util.List;
import java.util.UUID;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class AppFile extends BaseFile {
private DbObject appInfo;
private DbObject updateOptions;
@Transient
@Expose(
serialize = false
)
private boolean generateIcon;
public AppFile() {
this.generateIcon = true;
}
public AppFile(User user, UUID fileUuid, McFile file) {
this(user, fileUuid, file, true);
}
public AppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) {
super(user, fileUuid, file);
this.generateIcon = true;
this.generateIcon = generateIcon;
this.setAppInfo(file);
}
public boolean isApk() {
return !Strings.isNullOrEmpty(this.getPackageName());
}
public boolean hasSystemPermission() {
return "android.uid.system".equals(this.getSharedUserId());
}
public DbObject getAppInfo() {
if (this.appInfo == null) {
this.appInfo = new DbObject();
}
return this.appInfo;
}
public void setAppInfo(DbObject appInfo) {
this.appInfo = appInfo;
}
public void setAppInfo(String key, Object value) {
this.getAppInfo().append(key, value);
}
public DbObject getUpdateOptions() {
if (this.updateOptions == null) {
this.updateOptions = new DbObject();
}
return this.updateOptions;
}
public void setUpdateOptions(DbObject updateOptions) {
this.updateOptions = updateOptions;
}
public void setUpdateOptions(String key, Object value) {
this.getUpdateOptions().append(key, value);
}
public boolean isMitacApp() {
return this.getPackageName().toLowerCase().contains("mitac");
}
public String getPackageName() {
return this.getAppInfo().getString("packageName");
}
public void setPackageName(String packageName) {
this.setAppInfo("packageName", packageName);
}
public String getSharedUserId() {
return this.getAppInfo().getString("sharedUid");
}
public void setSharedUserId(String sharedUid) {
if (!Strings.isNullOrEmpty(sharedUid)) {
this.setAppInfo("sharedUid", sharedUid);
}
}
public String getLabel() {
return this.getAppInfo().getString("label");
}
public void setLabel(String label) {
this.setAppInfo("label", label);
}
public String getIconName() {
return this.getAppInfo().getString("iconName");
}
public void setIconName(String iconName) {
this.setAppInfo("iconName", iconName);
}
public long getVersionCode() {
return this.getAppInfo().getLong("versionCode");
}
public void setVersionCode(long versionCode) {
this.setAppInfo("versionCode", versionCode);
}
public String getVersionName() {
return this.getAppInfo().getString("versionName");
}
public void setVersionName(String versionName) {
this.setAppInfo("versionName", versionName);
}
public int getMinSdkVersion() {
return this.getAppInfo().getInteger("minSdkVersion", -1);
}
public void setMinSdkVersion(String minSdkVersion) {
if (!Strings.isNullOrEmpty(minSdkVersion)) {
this.setMinSdkVersion(Integer.parseInt(minSdkVersion));
}
}
public void setMinSdkVersion(int minSdkVersion) {
this.setAppInfo("minSdkVersion", minSdkVersion);
}
public int getMaxSdkVersion() {
return this.getAppInfo().getInteger("maxSdkVersion", -1);
}
public void setMaxSdkVersion(String maxSdkVersion) {
if (!Strings.isNullOrEmpty(maxSdkVersion)) {
this.setAppInfo("maxSdkVersion", Integer.parseInt(maxSdkVersion));
}
}
public int getTargetSdkVersion() {
return this.getAppInfo().getInteger("targetSdkVersion", -1);
}
public void setTargetSdkVersion(String targetSdkVersion) {
if (Strings.isNullOrEmpty(targetSdkVersion)) {
this.getAppInfo().remove("targetSdkVersion");
} else {
this.setAppInfo("targetSdkVersion", Integer.parseInt(targetSdkVersion));
}
}
public List getUserPermission() {
return this.getAppInfo().getList("userPermission", String.class);
}
public void setUserPermission(List userPermission) {
this.setAppInfo("userPermission", userPermission);
}
public String getCertMd5() {
return this.getAppInfo().getString("certMd5");
}
public void setCertMd5(String certMd5) {
if (!Strings.isNullOrEmpty(certMd5)) {
this.setAppInfo("certMd5", certMd5);
}
}
public void setAppInfo(McFile file) {
try {
McApkFile apkFile = new McApkFile(file);
ApkMeta meta = apkFile.getApkMeta();
this.setSharedUserId(meta.getSharedUserId());
this.setPackageName(meta.getPackageName());
String label = meta.getLabel();
if (Strings.isNullOrEmpty(label)) {
label = meta.getPackageName();
}
this.setLabel(label);
this.setVersionCode(meta.getVersionCode());
this.setVersionName(meta.getVersionName());
this.setUserPermission(meta.getUsesPermissions());
this.setMinSdkVersion(meta.getMinSdkVersion());
this.setMaxSdkVersion(meta.getMaxSdkVersion());
this.setTargetSdkVersion(meta.getTargetSdkVersion());
this.setCertMd5(apkFile.getCertMd5());
this.setName(this.getLabel());
if (this.generateIcon) {
apkFile.saveIcon(file.getPath() + ".png");
}
apkFile.close();
} catch (Exception var5) {
}
}
public void minify() {
super.minify();
this.setUserPermission((List)null);
this.setTargetSdkVersion((String)null);
this.setVersionName((String)null);
}
}
@@ -0,0 +1,279 @@
package com.midm.model.file;
import com.google.common.base.Strings;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.io.McFile;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.apache.tika.Tika;
import org.joda.time.LocalDateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class BaseFile {
@Id
protected UUID fileUuid;
protected UUID userUuid;
@Indexed
protected UUID siteUuid;
protected DbObject fileInfo;
protected DbObject extra;
protected String name;
protected boolean enabled = true;
protected Date lastUpdated;
protected Date registeredAt;
public BaseFile() {
}
public BaseFile(User user, UUID fileUuid, McFile file) {
this.setUserUuid(user);
this.setFileUuid(fileUuid);
this.setFileInfo(file);
this.initRegisteredAt();
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public UUID getFileUuid() {
return this.fileUuid;
}
public void setFileUuid(UUID uid) {
this.fileUuid = uid;
}
public UUID getUserUuid() {
return this.userUuid;
}
public void setUserUuid(UUID uid) {
this.userUuid = uid;
}
public void setUserUuid(User user) {
if (user != null) {
this.userUuid = user.getUuid();
}
}
public DbObject getFileInfo() {
if (this.fileInfo == null) {
this.fileInfo = new DbObject();
}
return this.fileInfo;
}
public String getFileInfoAsString(String key) {
if (this.fileInfo == null) {
this.fileInfo = new DbObject();
}
return this.fileInfo.getString(key);
}
public void removeFileInfo() {
this.fileInfo = null;
}
public void setFileInfo(DbObject fileInfo) {
this.fileInfo = fileInfo;
}
public void setFileInfo(McFile file) {
if (file.exists()) {
this.setLength(file.length());
this.setChecksum(file.getCrcChecksum());
this.setLastModified(file.lastModified());
}
}
public DbObject getExtra() {
return this.extra;
}
public void setExtra(DbObject extra) {
this.extra = extra;
}
public void setExtra(Map parameters) {
if (parameters != null) {
if (this.extra == null) {
this.extra = new DbObject();
}
parameters.forEach((key, value) -> {
if (value.length > 0 && key.startsWith("extra.")) {
this.extra.put(key.substring(6), value.length == 1 ? value[0] : Arrays.asList(value));
}
});
}
}
public boolean getEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getFileName() {
return this.getFileInfo().getString("fileName");
}
public void setFileName(String fileName) {
this.setFileInfo("fileName", fileName);
}
public String getContentType() {
String contentType = this.getFileInfo().getString("contentType");
if (Strings.isNullOrEmpty(contentType)) {
contentType = (new Tika()).detect(this.getFileName());
this.setType(contentType);
}
return contentType;
}
public void setType(String contentType) {
this.setFileInfo("contentType", contentType);
}
public long getLength() {
return this.getFileInfo().getLong("length");
}
public void setLength(long length) {
this.setFileInfo("length", length);
}
public long getChecksum() {
return this.getFileInfo().getLong("checksum");
}
public void setChecksum(long checksum) {
this.setFileInfo("checksum", checksum);
}
public long getLastModified() {
return this.getFileInfo().getLong("lastModified");
}
public void setLastModified(long lastModified) {
if (lastModified <= 0L) {
lastModified = (new Date()).getTime();
}
this.setFileInfo("lastModified", lastModified);
}
public void setFileInfo(String key, Object value) {
this.getFileInfo().append(key, value);
}
public void setFileUrl(String url) {
this.setFileInfo("fileUrl", url);
}
public long getUrlExpiry() {
Date expiry = this.getFileInfo().getDate("urlExpiry");
return expiry == null ? -1L : expiry.getTime();
}
public void setCloudUrl(String url) {
this.setFileInfo("fileUrl", url);
Date expiry = LocalDateTime.now().plusDays(6).toDate();
this.setFileInfo("urlExpiry", expiry);
}
public boolean hasFileUrl() {
boolean hasUrl = this.getFileInfo().containsKey("fileUrl");
if (hasUrl && this.getFileInfo().containsKey("urlExpiry")) {
hasUrl = this.getFileInfo().getDate("urlExpiry").after(new Date());
if (!hasUrl) {
this.getFileInfo().remove("fileUrl");
this.getFileInfo().remove("urlExpiry");
}
}
return hasUrl;
}
public String getFileUrl() {
return this.getFileInfoAsString("fileUrl");
}
public boolean hasIconUrl() {
boolean hasUrl = this.getFileInfo().containsKey("iconUrl");
if (hasUrl && this.getFileInfo().containsKey("iconExpiry")) {
hasUrl = this.getFileInfo().getDate("iconExpiry").after(new Date());
if (!hasUrl) {
this.getFileInfo().remove("iconUrl");
this.getFileInfo().remove("iconExpiry");
}
}
return hasUrl;
}
public void setIconUrl(String url) {
this.setFileInfo("iconUrl", url);
Date expiry = LocalDateTime.now().plusDays(6).toDate();
this.setFileInfo("iconExpiry", expiry);
}
public String getIconUrl() {
return this.getFileInfoAsString("iconUrl");
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Date getRegisteredAt() {
return this.registeredAt;
}
public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt;
}
public void initRegisteredAt() {
this.setRegisteredAt(new Date());
this.setLastUpdated(this.getRegisteredAt());
}
public void minify() {
this.userUuid = null;
this.registeredAt = null;
}
}
@@ -0,0 +1,81 @@
package com.midm.model.file;
public class DeployOption {
public static final String PROPERTY_DEFAULT = "default";
public static final String PROPERTY_FORCE_TO_DOWNLOAD = "force_to_download";
public static final String PROPERTY_FORCE_TO_INSTALL = "force_to_install";
public static final String PROPERTY_SAVE_AS = "save_as";
public static final String PROPERTY_KEEP_BACKUP = "keep_backgup";
private boolean isDefault;
private boolean uninstallFirst;
private boolean keepData;
private boolean forceToDownload;
private boolean foreceToInstall;
private String saveTo;
private boolean keepBackup;
private boolean isUserMode;
public boolean getIsDefault() {
return this.isDefault;
}
public void setIsDefault(boolean isDefault) {
this.isDefault = isDefault;
}
public boolean getUninstallFirst() {
return this.uninstallFirst;
}
public void setUninstallFirst(boolean uninstallFirst) {
this.uninstallFirst = uninstallFirst;
}
public boolean getKeepData() {
return this.keepData;
}
public void setKeepData(boolean keepData) {
this.keepData = keepData;
}
public boolean getForceToDownload() {
return this.forceToDownload;
}
public void setForceToDownload(boolean forceToDownload) {
this.forceToDownload = forceToDownload;
}
public boolean getForeceToInstall() {
return this.foreceToInstall;
}
public void setForeceToInstall(boolean foreceToInstall) {
this.foreceToInstall = foreceToInstall;
}
public String getSaveTo() {
return this.saveTo;
}
public void setSaveTo(String saveTo) {
this.saveTo = saveTo;
}
public boolean getKeepBackup() {
return this.keepBackup;
}
public void setKeepBackup(boolean keepBackup) {
this.keepBackup = keepBackup;
}
public boolean getIsUserMode() {
return this.isUserMode;
}
public void setIsUserMode(boolean isUserMode) {
this.isUserMode = isUserMode;
}
}
@@ -0,0 +1,9 @@
package com.midm.model.file;
public enum FILE_TYPE {
OTA,
REGION,
APK,
FILE,
UNKNOWN;
}
@@ -0,0 +1,784 @@
package com.midm.model.file;
import com.google.common.base.Strings;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.io.McFile;
import com.mitac.cell.security.McOtaCert;
import com.mitac.cell.utils.McJsonUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* ======================================================================================
* Android / 嵌入式系统 OTA 固件镜像模型 (OtaFile)
* ======================================================================================
*
* <p>【IoT 固件空中升级 (FOTA) 核心实现】
* 1. 业务功能:
* - 管理受控终端的完整系统固件镜像(System Image / Full OTA)与区域增量镜像(Region Image / Incremental OTA)。
* 2. 【固件安全与包结构解析】:
* - 自动解包并解析 Android Recovery 规范的标准固件 ZIP 包结构:
* - `META-INF/com/google/android/updater-script`: 固件升级执行脚本;
* - `system/build.prop`: 提取目标硬件型号、Android 操作系统版本、编译日期(build_date)、基带版本等;
* - `META-INF/com/android/otacert`: 嵌入式固件发布签名证书,校验固件是否由官方私钥签发;
* - `META-INF/com/android/metadata`: 提取差分升级的前置版本与兼容约束。
* 3. 硬件兼容性矩阵(SKU Matching):
* - 严格匹配终端出厂 SKU,防止跨机型错刷固件导致设备“变砖”(Bricking)。
*
* @author MiDM Core Platform Team
*/
@Document
public class OtaFile extends BaseFile implements Comparable {
/** Android Recovery 固件升级脚本入口 */
private static final String ENTRY_META_INF = "META-INF/com/";
private static final String ENTRY_UPDATE_SCRIPT = "META-INF/com/google/android/updater-script";
/** Android 操作系统属性字典路径(包含型号、Build版本、指纹等关键参数) */
private static final String ENTRY_BUILD_PROP = "system/build.prop";
/** 固件合法性验签 X.509 官方证书路径 */
private static final String ENTRY_OTA_CERT = "META-INF/com/android/otacert";
/** OTA 元数据配置文件(版本区间、差分基线版本等) */
private static final String ENTRY_METADATA = "META-INF/com/android/metadata";
private static final String ENTRY_UPDATE_INFO = "META-INF/com/android/update_info";
/** 解析固件包后提取的硬件规格与构建元数据字典 */
private DbObject otaInfo;
public OtaFile() {
}
public OtaFile(User user, UUID fileUuid, McFile file) {
super(user, fileUuid, file);
this.setOtaInfo(file);
}
public boolean isOtaImage() {
if (Strings.isNullOrEmpty(this.getProductId()) && Strings.isNullOrEmpty(this.getDeviceId())) {
return false;
} else {
return this.isRegionImage() ? true : !Strings.isNullOrEmpty(this.getSkuId());
}
}
public DbObject getOtaInfo() {
if (this.otaInfo == null) {
this.otaInfo = new DbObject();
}
return this.otaInfo;
}
public void setOtaInfo(DbObject otaInfo) {
this.otaInfo = otaInfo;
}
public void setOtaInfo(String key, Object value) {
this.getOtaInfo().append(key, value);
}
public void setOtaInfo(McFile file) {
try {
this.retrieveBuildInfo(new ZipFile(file));
} catch (Exception var3) {
}
}
public String getType() {
return this.getOtaInfo().getString("type", "system");
}
public boolean isSystemImage() {
return this.getType().equals("system");
}
public boolean isRegionImage() {
return this.getType().equals("region");
}
public boolean isModemImage() {
return this.getType().equals("modem");
}
public boolean isAbUpdate() {
return this.getOtaInfo().getBoolean("abUpdate", false);
}
public boolean isPartial() {
return this.getOtaInfo().containsKey("preBuild");
}
public void setType(String type) {
if (type.toLowerCase().equals("base")) {
type = "system";
}
this.getOtaInfo().put("type", type);
}
public void setAbUpdate(boolean abUpdate) {
this.getOtaInfo().put("abUpdate", abUpdate);
}
public long getBuildDate() {
return this.getOtaInfo().getLong("buildDate", -1L);
}
public void setBuildDate(long date) {
this.setOtaInfo("buildDate", date);
}
public int getSdkLevel() {
return this.getOtaInfo().getInteger("sdk", -1);
}
public void setSdkLevel(int level) {
this.setOtaInfo("sdk", level);
}
public long getPostBuildDate() {
return this.getOtaInfo().getLong("postBuildDate", -1L);
}
public void setPostBuildDate(long date) {
this.setOtaInfo("postBuildDate", date);
}
public String getProductId() {
return this.getOtaInfo().getString("productId");
}
public void setProductId(String productId) {
this.setOtaInfo("productId", productId);
}
public String getTargetProduct() {
return this.getOtaInfo().getString("targetProduct");
}
public void setTargetProduct(String productId) {
this.setOtaInfo("targetProduct", productId);
}
public String getSkuId() {
return this.getOtaInfo().getString("skuId");
}
public void setSkuId(String skuId) {
this.setOtaInfo("skuId", skuId);
}
public boolean hasCompatibleSkuIds() {
List<String> ids = this.getOtaInfo().getList("compatibleSkuIds", String.class);
return ids != null && ids.size() > 0;
}
public List getCompatibleSkuIds() {
return this.getOtaInfo().getList("compatibleSkuIds", String.class);
}
public boolean isCompatibleSkuId(String skuId) {
if (Strings.isNullOrEmpty(skuId)) {
return false;
} else {
String curSkuId = this.getSkuId();
if (skuId.equals(curSkuId)) {
return true;
} else {
List<String> compatibleSkuIds = this.getCompatibleSkuIds();
return compatibleSkuIds != null && compatibleSkuIds.contains(skuId);
}
}
}
public void setCompatibleSkuIds(String skuIds) {
if (!Strings.isNullOrEmpty(skuIds)) {
String[] ids = skuIds.split("\\s*,\\s*");
if (ids != null && ids.length > 0) {
this.setOtaInfo("compatibleSkuIds", Arrays.asList(ids));
}
}
}
public String getDeviceId() {
return this.getOtaInfo().getString("deviceId");
}
public void setDeviceId(String deviceId) {
this.setOtaInfo("deviceId", deviceId);
}
public String getDisplayId() {
return this.getOtaInfo().getString("displayId");
}
public void setDisplayId(String displayId) {
this.setOtaInfo("displayId", displayId);
}
public void setProductDisplayId(String displayId) {
this.setOtaInfo("productDisplayId", displayId);
}
public String getPreDisplayId() {
return this.getOtaInfo().getString("preDisplayId");
}
public void setPreDisplayId(String displayId) {
this.setOtaInfo("preDisplayId", displayId);
}
public static String parseSkuId(String displayId) {
if (displayId != null) {
int startIndex = displayId.indexOf(46);
++startIndex;
startIndex = displayId.indexOf(46, startIndex);
if (startIndex > 0) {
int endIndex = displayId.indexOf(46, startIndex + 1);
if (endIndex > startIndex) {
++startIndex;
return displayId.substring(startIndex, endIndex);
}
}
}
return null;
}
public String getBrand() {
return this.getOtaInfo().getString("brand");
}
public void setBrand(String brand) {
this.setOtaInfo("brand", brand);
}
public String getCustomer() {
return this.getOtaInfo().getString("customer");
}
public void setCustomer(String customer) {
this.setOtaInfo("customer", customer);
}
public String getCustomerId() {
return this.getOtaInfo().getString("customerId");
}
public void setCustomerId(String customerId) {
this.setOtaInfo("customerId", customerId);
}
public String getPartNo() {
return this.getOtaInfo().getString("partNo");
}
public void setPartNo(String partNo) {
this.setOtaInfo("partNo", partNo);
}
public String getOsVersion() {
return this.getOtaInfo().getString("osVersion");
}
public void setOsVersion(String version) {
this.setOtaInfo("osVersion", version);
}
public String getScriptVersion() {
return this.getOtaInfo().getString("scriptVersion");
}
public void setScriptVersion(String partNo) {
this.setOtaInfo("scriptVersion", partNo);
}
public String getReleaseVersion() {
return this.getOtaInfo().getString("releaseVersion");
}
public void setReleaseVersion(String partNo) {
this.setOtaInfo("releaseVersion", partNo);
}
public String getMarketName1() {
return this.getOtaInfo().getString("marketName1");
}
public void setMarketName1(String name) {
this.setOtaInfo("marketName1", name);
}
public String getMarketName2() {
return this.getOtaInfo().getString("marketName2");
}
public void setMarketName2(String name) {
this.setOtaInfo("marketName2", name);
}
public String getSecurityPatchLevel() {
return this.getOtaInfo().getString("securityPatch");
}
public void setSecurityPatchLevel(String level) {
this.setOtaInfo("securityPatch", level);
}
public String getBuildType() {
return this.getOtaInfo().getString("buildType");
}
public void setBuildType(String buildType) {
this.setOtaInfo("buildType", buildType);
}
public String getBuildTags() {
return this.getOtaInfo().getString("buildTags");
}
public void setBuildTags(String buildTags) {
this.setOtaInfo("buildTags", buildTags);
}
public String getPreBuild() {
return this.getOtaInfo().getString("preBuild");
}
public void setPreBuild(String value) {
this.setOtaInfo("preBuild", value);
}
public String getOtaCertHash() {
return this.getOtaInfo().getString("otaCert");
}
public void setOtaCertHash(String hash) {
this.setOtaInfo("otaCert", hash);
}
public String getModemSku() {
return this.getOtaInfo().getString("modemSku");
}
public void setModemSku(String hash) {
this.setOtaInfo("modemSku", hash);
}
public String getModemFirmwareVersion() {
return this.getOtaInfo().getString("modemFirmwareVersion");
}
public void setModemFirmwareVersion(String hash) {
this.setOtaInfo("modemFirmwareVersion", hash);
}
public String getModemFirmwareLongVersion() {
return this.getOtaInfo().getString("modemFirmwareLongVersion");
}
public void setModemFirmwareLongVersion(String hash) {
this.setOtaInfo("modemFirmwareLongVersion", hash);
}
private void retrieveBuildInfo(ZipFile zipFile) {
try {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
ZipEntry bodyEntry = null;
boolean isAbImage = false;
while(entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.getName().endsWith(".zip")) {
bodyEntry = entry;
} else if (entry.getName().endsWith(".sh")) {
isAbImage = true;
}
}
if (isAbImage && bodyEntry != null) {
InputStream input = zipFile.getInputStream(bodyEntry);
ZipInputStream zipBody;
ZipEntry entry;
for(zipBody = new ZipInputStream(input); (entry = zipBody.getNextEntry()) != null; zipBody.closeEntry()) {
String entryName = entry.getName();
if (entryName.equals("META-INF/com/android/metadata")) {
this.dispatchProp(zipBody);
} else if (entryName.equals("META-INF/com/android/update_info")) {
this.dispatchJson(zipBody);
} else if (entryName.equals("META-INF/com/android/otacert")) {
this.dispatchOtaCert(zipBody);
}
}
zipBody.close();
input.close();
} else {
ZipEntry udpateInfoEntry = zipFile.getEntry("META-INF/com/android/update_info");
if (udpateInfoEntry != null) {
this.dispatchJson(zipFile.getInputStream(udpateInfoEntry));
this.setType("region");
}
ZipEntry metaDataEntry = zipFile.getEntry("META-INF/com/android/metadata");
if (metaDataEntry != null) {
this.dispatchProp(zipFile.getInputStream(metaDataEntry));
}
ZipEntry updateScriptEntry = zipFile.getEntry("META-INF/com/google/android/updater-script");
if (updateScriptEntry != null) {
this.dispatchUpdaterScript(zipFile.getInputStream(updateScriptEntry));
}
ZipEntry otaCertEntry = zipFile.getEntry("META-INF/com/android/otacert");
if (otaCertEntry != null) {
InputStream otaInput = zipFile.getInputStream(otaCertEntry);
this.dispatchOtaCert(otaInput);
otaInput.close();
}
ZipEntry buildPropEntry = zipFile.getEntry("system/build.prop");
if (buildPropEntry != null) {
this.dispatchProp(zipFile.getInputStream(buildPropEntry));
}
zipFile.close();
if (!Strings.isNullOrEmpty(this.getDisplayId()) && this.isRegionImage()) {
this.setDisplayId(String.format("%s_%s_%s", this.getReleaseVersion(), this.getPartNo(), this.getMarketName2()));
}
if (Strings.isNullOrEmpty(this.getType())) {
this.setType("system");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void dispatchUpdaterScript(InputStream is) {
try {
String script = IOUtils.toString(is, "UTF-8");
String key = "ro.build.date.utc";
String buildDate = this.lastSubString(script, key, "(", ",");
this.setOtaProperty(key, buildDate);
key = "ro.product.device";
String value = this.subString(script, key, "\"", "\"");
if (!Strings.isNullOrEmpty(value)) {
this.setOtaProperty(key, value);
}
key = "ro.mitac.product";
value = this.subString(script, key, "\"", "\"");
if (!Strings.isNullOrEmpty(value)) {
this.setOtaProperty(key, value);
}
key = "ro.mitac.sku";
value = this.subString(script, key, "\"", "\"");
if (!Strings.isNullOrEmpty(value)) {
this.setOtaProperty(key, value);
}
if (Strings.isNullOrEmpty(this.getDeviceId())) {
value = this.subString(script, "get_device_compatible", "\"", "\"");
if (!Strings.isNullOrEmpty(value)) {
this.setDeviceId(value);
}
}
if (Strings.isNullOrEmpty(this.getBuildTags())) {
String fingerPrint = this.subString(script, "ui_print(\"Target", " ", "\"");
if (!Strings.isNullOrEmpty(fingerPrint)) {
String buildTags = fingerPrint.substring(fingerPrint.lastIndexOf(47) + 1);
if (!Strings.isNullOrEmpty(buildTags)) {
this.setBuildTags(buildTags);
}
}
}
} catch (IOException var8) {
}
}
private void dispatchProp(InputStream input) {
try {
Properties properties = new Properties();
properties.load(input);
for(Map.Entry entry : properties.entrySet()) {
this.setOtaProperty((String)entry.getKey(), (String)entry.getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void dispatchJson(InputStream input) {
if (input != null) {
JsonElement json = McJsonUtils.toJsonElement(input);
if (json != null && json.isJsonObject()) {
JsonObject jProps = json.getAsJsonObject();
for(Map.Entry entry : jProps.entrySet()) {
String key = (String)entry.getKey();
JsonElement value = (JsonElement)entry.getValue();
if (value.isJsonPrimitive()) {
this.setOtaProperty(key, value.getAsString());
}
}
}
}
}
private void dispatchOtaCert(InputStream otaCertIs) {
McOtaCert otaCert = new McOtaCert(otaCertIs);
this.setOtaCertHash(otaCert.getBase64Hash());
}
private void setOtaProperty(String key, String value) {
switch (key) {
case "ota-type":
this.setAbUpdate(value.equals("AB"));
break;
case "persist.sys.rgimg.brand":
if (Strings.isNullOrEmpty(this.getBrand())) {
this.setBrand(value);
}
break;
case "ro.build.date.utc":
case "post-timestamp":
case "persist.sys.rgimg.build_utc":
if (this.getBuildDate() < 0L) {
this.setBuildDate(Long.valueOf(value));
}
break;
case "persist.sys.rgimg.customer":
if (Strings.isNullOrEmpty(this.getCustomer())) {
this.setCustomer(value);
}
break;
case "persist.sys.rgimg.customer_id":
if (Strings.isNullOrEmpty(this.getCustomerId())) {
this.setCustomerId(value);
}
break;
case "persist.sys.rgimg.mkt_name1":
if (Strings.isNullOrEmpty(this.getMarketName1())) {
this.setMarketName1(value);
}
break;
case "persist.sys.rgimg.mkt_name2":
if (Strings.isNullOrEmpty(this.getMarketName2())) {
this.setMarketName2(value);
}
break;
case "persist.sys.rgimg.part_num":
if (Strings.isNullOrEmpty(this.getPartNo())) {
this.setPartNo(value);
}
break;
case "product-code":
case "ro.mitac.product":
case "persist.sys.rgimg.product":
if (Strings.isNullOrEmpty(this.getProductId())) {
this.setProductId(value);
}
break;
case "persist.sys.rgimg.release_ver":
if (Strings.isNullOrEmpty(this.getReleaseVersion())) {
this.setReleaseVersion(value);
}
break;
case "persist.sys.rgimg.script_ver":
if (Strings.isNullOrEmpty(this.getScriptVersion())) {
this.setScriptVersion(value);
}
break;
case "persist.sys.rgimg.target_device":
case "pre-device":
if (Strings.isNullOrEmpty(this.getDeviceId())) {
this.setDeviceId(value);
}
break;
case "persist.sys.rgimg.target_product":
if (Strings.isNullOrEmpty(this.getTargetProduct())) {
this.setTargetProduct(value);
}
break;
case "mitac-display-id":
String curDisplayId = this.getDisplayId();
this.setProductDisplayId(value);
if (Strings.isNullOrEmpty(curDisplayId)) {
this.setDisplayId(value);
}
if (Strings.isNullOrEmpty(this.getSkuId())) {
String skuId = parseSkuId(value);
if (!Strings.isNullOrEmpty(skuId)) {
this.setSkuId(skuId);
}
}
break;
case "display-id":
case "ro.build.display.id":
String curDisplayId = this.getDisplayId();
if (Strings.isNullOrEmpty(curDisplayId) || !curDisplayId.equals(value)) {
this.setDisplayId(value);
}
if (Strings.isNullOrEmpty(this.getSkuId())) {
String skuId = parseSkuId(value);
if (!Strings.isNullOrEmpty(skuId)) {
this.setSkuId(skuId);
}
}
break;
case "pre-display-id":
this.setPreDisplayId(value);
break;
case "mitac-package-type":
this.setType(value);
case "post-build-incremental":
default:
break;
case "post-sdk-level":
if (this.getSdkLevel() < 0) {
this.setSdkLevel(Integer.valueOf(value));
}
break;
case "post-security-patch-level":
if (Strings.isNullOrEmpty(this.getSecurityPatchLevel())) {
this.setSecurityPatchLevel(value);
}
break;
case "pre-build":
this.setPreBuild(value);
break;
case "post-build":
this.dispatchPostBuild(value);
break;
case "sku-id":
case "ro.mitac.sku":
this.setSkuId(value);
break;
case "base-sku-compatibility":
if (!this.hasCompatibleSkuIds()) {
this.setCompatibleSkuIds(value);
}
break;
case "ro.build.tags":
if (Strings.isNullOrEmpty(this.getBuildTags())) {
this.setBuildTags(value);
}
break;
case "modem-firmware-sku":
if (Strings.isNullOrEmpty(this.getModemSku())) {
this.setModemSku(value);
}
break;
case "modem-firmware-version":
if (Strings.isNullOrEmpty(this.getModemFirmwareVersion())) {
this.setModemFirmwareVersion(value);
}
break;
case "modem-firmware-long-version":
if (Strings.isNullOrEmpty(this.getModemFirmwareLongVersion())) {
this.setModemFirmwareLongVersion(value);
}
}
}
public String getPostBuild() {
return this.getOtaInfo().getString("postBuild");
}
private void dispatchPostBuild(String text) {
this.setOtaInfo("postBuild", text);
String[] tags = text.split(":");
if (tags.length >= 3) {
String[] tokens = tags[1].split("/");
if (Strings.isNullOrEmpty(this.getOsVersion())) {
this.setOsVersion(tokens[0]);
}
tokens = tags[2].split("/");
if (Strings.isNullOrEmpty(this.getBuildType())) {
this.setBuildType(tokens[0]);
}
if (Strings.isNullOrEmpty(this.getBuildTags())) {
this.setBuildTags(tokens[1]);
}
}
}
private String subString(String sb, String key, String prefix, String suffix) {
int keyIndex = sb.indexOf(key);
if (keyIndex < 0) {
return null;
} else {
int startIndex = sb.indexOf(prefix, keyIndex + key.length() + 1) + 1;
int endIndex = sb.indexOf(suffix, startIndex + 1);
return startIndex < endIndex ? sb.substring(startIndex, endIndex) : "";
}
}
private String lastSubString(String sb, String key, String prefix, String suffix) {
int keyIndex = sb.indexOf(key);
int endIndex = sb.lastIndexOf(",", keyIndex);
int startIndex = sb.lastIndexOf("(", endIndex) + 1;
return startIndex < endIndex ? sb.substring(startIndex, endIndex) : "";
}
public int compareTo(OtaFile other) {
int result = this.getSkuId().compareTo(other.getSkuId());
if (result == 0) {
boolean isThisSystemImage = this.isSystemImage();
boolean isOtherSystemImage = other.isSystemImage();
if (isThisSystemImage != isOtherSystemImage) {
if (isThisSystemImage) {
return -1;
}
return 1;
}
result = (int)(this.getBuildDate() - other.getBuildDate());
if (result == 0) {
if (this.isPartial() && !other.isPartial()) {
return -1;
}
if (!this.isPartial() && other.isPartial()) {
return 1;
}
}
}
return result;
}
}
@@ -0,0 +1,37 @@
package com.midm.model.file;
import java.util.List;
public enum REPORT_ERROR {
UNKNOWN(1000),
FILE_ERROR(1001),
UNHANDLED_HTTP_CODE(1002),
HTTP_DATA_ERROR(1004),
TOO_MANY_REDIRECTS(1005),
INSUFFICIENT_SPACE(1006),
DEVICE_NOT_FOUND(1007),
CANNOT_RESUME(1008),
FILE_ALREADY_EXISTS(1009),
FILE_MISMATCHED(2001);
public static final List COLLECT_SSN = List.of(UNKNOWN, FILE_ERROR, INSUFFICIENT_SPACE, DEVICE_NOT_FOUND, CANNOT_RESUME, FILE_ALREADY_EXISTS);
private int value;
private REPORT_ERROR(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static REPORT_ERROR fromValue(int value) {
for(REPORT_ERROR e : values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
}
@@ -0,0 +1,142 @@
package com.midm.model.log;
import com.google.common.base.Strings;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.internet.http.UserAgent;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@CompoundIndexes({@CompoundIndex(
def = "{'category':1, 'loggedAt':1}"
), @CompoundIndex(
def = "{'forWhat':1, 'loggedAt': -1}"
), @CompoundIndex(
def = "{'forWhat':1, 'log': 1}"
)})
public class MidmLog {
@Id
private UUID uuid;
private UUID forWhat;
private String category;
private String log;
private DbObject reference;
private Date loggedAt;
@DBRef
private User logger;
public MidmLog() {
this.setUuid(UUID.randomUUID());
this.setLoggedAt(new Date());
}
public MidmLog(User user, UUID forWhat, String category, String log) {
this();
if (user != null) {
this.setLogger(user);
}
this.setForWhat(forWhat);
this.setCategory(category);
this.setLog(log);
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getForWhat() {
return this.forWhat;
}
public void setForWhat(UUID forWhat) {
this.forWhat = forWhat;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLog() {
return this.log;
}
public void setLog(String log) {
this.log = log;
}
public DbObject getReference() {
if (this.reference == null) {
this.reference = new DbObject();
}
return this.reference;
}
public boolean hasReference() {
return this.reference != null && this.reference.size() > 0;
}
public void setReference(DbObject reference) {
this.reference = reference;
}
public void setReference(UserAgent agent, String sessionId, String remoteIp) {
if (agent != null) {
this.addReference("browser", agent.agentFamily());
this.addReference("os", agent.osFamily());
this.addReference("device", agent.deviceFamily());
}
if (!Strings.isNullOrEmpty(sessionId)) {
this.addReference("sessionId", sessionId);
}
if (!Strings.isNullOrEmpty(remoteIp)) {
this.addReference("remoteIp", remoteIp);
}
}
public void addReference(String key, Object value) {
this.getReference().put(key, value);
}
public UUID getLoggerUuid() {
return this.logger != null ? this.logger.getUuid() : null;
}
public Date getLoggedAt() {
return this.loggedAt;
}
public void setLoggedAt(Date loggedAt) {
this.loggedAt = loggedAt;
}
public void setLoggedAt(long loggedAt) {
this.loggedAt = new Date(loggedAt);
}
public User getLogger() {
return this.logger;
}
public void setLogger(User logger) {
this.logger = logger;
}
}
@@ -0,0 +1,59 @@
package com.midm.model.message;
public enum MIDM_REQUEST {
PING(99, "ping"),
CONNECT(100, "connect"),
DISCONNECT(101, "disconnect"),
CHECKIN(102, "checkin"),
CHECKOUT(103, "checkout"),
ENROLL(104, "enroll"),
DEVICE_INFO(105, "update_device_info"),
CLIENT_UPDATE(121, "client_update"),
UPDATE_PROFILE(131, "profile_update"),
UPDATE_ALL_PROFILES(132, "profile_update_all"),
REMOVE_PROFILE(136, "profile_remove"),
COMMAND(200, "command"),
QUERY(210, "query"),
EXEC(220, "exec"),
DEVICE_STATE(300, "device_state"),
USER_LOG(301, "userLog"),
DEVICE_LOG(302, "deviceLog"),
RTC(400, "rtc"),
UNKNOWN(-1, "");
private int code;
private String request;
private MIDM_REQUEST(int code, String request) {
this.code = code;
this.request = request;
}
public int getCode() {
return this.code;
}
public String getRequest() {
return this.request;
}
public static MIDM_REQUEST get(int code) {
for(MIDM_REQUEST request : values()) {
if (request.code == code) {
return request;
}
}
return UNKNOWN;
}
public static MIDM_REQUEST get(String requestText) {
for(MIDM_REQUEST request : values()) {
if (request.getRequest().equalsIgnoreCase(requestText.trim())) {
return request;
}
}
return UNKNOWN;
}
}
@@ -0,0 +1,135 @@
package com.midm.model.message;
import com.google.common.base.Charsets;
import com.mitac.cell.data.McCompress;
import com.mitac.cell.data.McDecompress;
import com.mitac.cell.utils.McJsonUtils;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
@Document
public class MidmPacket implements Serializable {
@Id
private UUID uuid;
private UUID recieverUuid;
private UUID queryUuid;
@Transient
private MidmQuery query;
private MidmResponse feedback;
private Date readAt;
public MidmPacket() {
this.setUuid(UUID.randomUUID());
}
public MidmPacket(int code) {
this.init();
this.setQuery(new MidmQuery(code));
}
public MidmPacket(MIDM_REQUEST request) {
this(request.getCode());
}
private void init() {
this.setUuid(UUID.randomUUID());
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getRecieverUuid() {
return this.recieverUuid;
}
public void setRecieverUuid(UUID recieverUuid) {
this.recieverUuid = recieverUuid;
}
public UUID getQueryUuid() {
return this.queryUuid;
}
public void setQueryUuid(UUID queryUuid) {
this.queryUuid = queryUuid;
}
public MidmQuery getQuery() {
return this.query;
}
public void setQuery(MidmQuery query) {
this.query = query;
}
public Object getParam(String key) {
return this.getQuery().getParam(key);
}
public void setParam(String key, Object value) {
this.getQuery().setParam(key, value);
}
public MidmResponse getFeedback() {
return this.feedback;
}
public void setFeedback(MidmResponse feedback) {
this.feedback = feedback;
}
public void setFeedback(int code, String message) {
this.feedback = new MidmResponse(code, message);
}
public void setFeedback(int code, String message, Object data) {
this.feedback = new MidmResponse(code, message, data);
}
public Date getReadAt() {
return this.readAt;
}
public void setReadAt(Date readAt) {
this.readAt = readAt;
}
public TextMessage toMessage() {
return new TextMessage(this.toString());
}
public BinaryMessage toBinary() {
byte[] bytes = McCompress.compress(this.toString());
return new BinaryMessage(bytes);
}
public String toString() {
return McJsonUtils.toJson(this);
}
public static MidmPacket toPacket(TextMessage message) {
return (MidmPacket)McJsonUtils.toObject((String)message.getPayload(), MidmPacket.class);
}
public static MidmPacket topacket(BinaryMessage message) {
ByteBuffer bytes = (ByteBuffer)message.getPayload();
byte[] decompressed = McDecompress.decompress(bytes.array());
return (MidmPacket)McJsonUtils.toObject(new String(decompressed, Charsets.UTF_8), MidmPacket.class);
}
public static MidmPacket toPacket(String message) {
return (MidmPacket)McJsonUtils.toObject(message, MidmPacket.class);
}
}
@@ -0,0 +1,113 @@
package com.midm.model.message;
import com.mitac.cell.db.DbObject;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class MidmQuery {
private UUID uuid;
private UUID senderUuid;
private int code;
private DbObject query;
private boolean isInstant;
private Date registeredAt;
public MidmQuery() {
this.init();
}
public MidmQuery(int code) {
this();
this.setCode(code);
}
public void init() {
this.setUuid(UUID.randomUUID());
this.isInstant = true;
this.setRegisteredAt(new Date());
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public UUID getSenderUuid() {
return this.senderUuid;
}
public void setSenderUuid(UUID senderUuid) {
this.senderUuid = senderUuid;
}
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
public DbObject getQuery() {
if (this.query == null) {
this.query = new DbObject();
}
return this.query;
}
public void setQuery(DbObject query) {
this.query = query;
}
public String getRequest() {
return (String)this.getQuery().get("request");
}
public void setRequest(String request) {
this.getQuery().put("request", request);
}
public DbObject getParams() {
DbObject params = this.getQuery().getDbObject(new String[]{"params"});
if (params == null) {
params = new DbObject();
this.getQuery().put("params", params);
}
return params;
}
public Object getParam(String key) {
return this.getParams().get(key);
}
public String getCommand() {
return this.getParam("command").toString();
}
public void setParam(String key, Object value) {
this.getParams().put(key, value);
}
public boolean isInstant() {
return this.isInstant;
}
public void setInstant(boolean isInstant) {
this.isInstant = isInstant;
}
public Date getRegisteredAt() {
return this.registeredAt;
}
public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt;
}
}
@@ -0,0 +1,268 @@
package com.midm.model.message;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McJsonUtils;
import com.mongodb.client.result.UpdateResult;
import java.util.List;
import java.util.Map;
import org.springframework.data.domain.Page;
import org.springframework.web.socket.TextMessage;
public class MidmResponse {
public static final String MESSAGE_SUCCEED = "succeed";
public static final String MESSAGE_FAILED = "failed";
public static final int CODE_SERVICE_CONNECTED = 100;
public static final int CODE_SUCCEED = 200;
public static final int CODE_CHECKEDIN = 110;
public static final int CODE_ENROLLED = 111;
public static final int CODE_ENROLL_REJECTED = 112;
public static final int CODE_DEVICE_REGISTERD = 113;
public static final int CODE_DEVICE_UPDATED = 114;
public static final int CODE_LICENSE_EXPIRED = 115;
public static final int CODE_MESSAGE_NOTIFY = 116;
public static final int CODE_REPORT_READY = 117;
public static final int CODE_REPORT_GENERATE_FAIL = 118;
public static final int CODE_HOST_LICENSE_READY = 119;
public static final int CODE_SITE_LICENSE_READY = 109;
public static final int CODE_SITE_LICENSE_REQUESTED = 108;
public static final int CODE_SITE_UPGRADE_REQUESTED = 107;
public static final int CODE_SITE_UPGRADE_SUCCESS = 106;
public static final int CODE_UPDATE_CIENT_APPS = 121;
public static final int CODE_ONLINE_STATE_CHANGED = 211;
public static final int CODE_DEVICE_STATE_CHANGED = 300;
public static final int FEEDBACK_APP_LIST = 120;
public static final int FEEDBACK_APP_INSTALLED = 121;
public static final int FEEDBACK_APP_UNINSTALLED = 122;
public static final int FEEDBACK_APP_ENABLE = 123;
public static final int FEEDBACK_APP_DISABLE = 124;
public static final int FEEDBACK_APP_SHOW = 125;
public static final int FEEDBACK_APP_HIDE = 126;
public static final int FEEDBACK_APP_INFO = 127;
public static final int FEEDBACK_FILE_LIST = 130;
public static final int FEEDBACK_FILE_STORAGE = 131;
public static final int FEEDBACK_FILE_COPY = 132;
public static final int FEEDBACK_FILE_RENAME = 133;
public static final int FEEDBACK_FILE_MOVE = 134;
public static final int FEEDBACK_FILE_REMOVE = 135;
public static final int FEEDBACK_FILE_MKDIR = 136;
public static final int FEEDBACK_FILE_PUSH = 137;
public static final int FEEDBACK_FILE_PULL = 138;
public static final int FEEDBACK_FILE_LOGCAT = 139;
public static final int FEEDBACK_EXEC = 140;
public static final int FEEDBACK_EXEC_LOGCAT = 141;
public static final int FEEDBACK_HARDWARE_INFO = 170;
public static final int FEEDBACK_SOFTWARE_INFO = 180;
public static final int FEEDBACK_MEMORY_USAGE = 190;
public static final int FEEDBACK_BATTERY_INFO = 191;
public static final int FEEDBACK_DATA_USAGE = 192;
public static final int FEEDBACK_ACTIVE_NETWORK = 193;
public static final int FEEDBACK_NETWORK = 194;
public static final int FEEDBACK_LOCATION = 198;
public static final int FEEDBACK_SCREEN_CAPTURED = 199;
public static final int FEEDBACK_ONLINE_STATE = 211;
public static final int FEEDBACK_CAMERA_STATE = 212;
public static final int FEEDBACK_DEVICE_STATE = 300;
public static final int CODE_FAILED = 400;
public static final int CODE_NOT_FOUND = 404;
public static final int CODE_FAIL_USER_NOT_FOUND = 410;
public static final int CODE_FAIL_WRONG_PASSWROD = 411;
public static final int CODE_FAIL_USER_NOT_AVAILABLE = 412;
public static final int CODE_FAIL_INSUFFICIENT_INFO = 413;
public static final int CODE_FAIL_USER_LOGGED_IN = 414;
public static final int CODE_FAIL_NO_AUTH_INFO = 415;
public static final int CODE_FAIL_REGISTERED_TO_OTHER = 416;
public static final int CODE_FAIL_VERSION_DUPLICATE = 417;
public static final int CODE_FAIL_USER_NOT_AGREED = 418;
public static final int CODE_FAIL_SAME_NAME_NOT_ALLOW = 419;
public static final int CODE_FAIL_HOST_EXPIRED = 420;
public static final int CODE_FAIL_HOST_EXCEED_DEVICE_LIMIT = 421;
public static final int CODE_FAIL_INVALID = 422;
public static final int CODE_FAIL_EXISTING_USER = 423;
public static final int CODE_FAIL_EXCEED_LOGIN_FAILURE = 424;
public static final int CODE_FAIL_API_ONLY_USER = 425;
public static final int CODE_FAIL_SITE_NOT_FOUND = 450;
public static final int CODE_FAIL_NO_SITE_AVAILABLE = 451;
public static final int CODE_FAIL_SITE_NO_USER = 452;
public static final int CODE_FAIL_SITE_USER_DISABLED = 453;
public static final int CODE_FAIL_SITE_SAME = 455;
public static final int CODE_FAIL_DEVICE_NO_SERIAL = 461;
public static final int CODE_FAIL_DEVICE_NO_SITE = 462;
public static final int CODE_FAIL_NO_DEVICE_EXISTS = 463;
public static final int CODE_FAIL_DEVICE_NO_LICENSE = 464;
public static final int CODE_FAIL_CHILD_EXISTS = 466;
public static final int CODE_FAIL_DEVICE_EXISTS = 467;
public static final int CODE_FAIL_LICENSE_EXPIRED = 115;
public static final int CODE_ERROR_NO_RECORD = 421;
public static final int CODE_ERROR_TOKEN_NOT_DEFINED = 461;
public static final int CODE_ERROR_EXPIRED_TOKEN = 462;
public static final int CODE_ERROR_INVALID_TOKEN = 463;
public static final int CODE_ERROR_URL_FORMAT = 431;
public static final int CODE_ERROR_IO_EXEPTION = 432;
public static final int CODE_ERROR_NO_PERMISSION = 433;
public static final int CODE_ERROR_INVALID_SYSTEM_IMAGE = 441;
public static final int CODE_UNKOWN = -1;
public static final String MESSAGE_NOT_ALLOWED = "Not allowed.";
public static final String MESSAGE_NOT_AUTHORIZED = "Not authorized.";
public static final String MESSAGE_NO_PERMISSION = "No permission.";
public static final String MESSAGE_NO_USER_EXISTS = "No user exists.";
public static final String MESSAGE_NO_SITE_AVAILABLE = "No site available.";
public static final String MESSAGE_NO_DEVICE_EXISTS = "No device exists.";
public static final String MESSAGE_NO_SERIAL_DEFINED = "No serial no. defined.";
public static final String MESSAGE_DEVICE_EXISTS = "Existing device.";
public static final String MESSAGE_NO_GROUP_EXISTS = "No group exists.";
public static final String MESSAGE_NO_GROUP = "No group: ";
public static final String MESSAGE_NO_RECORDS = "No records.";
public static final String MESSAGE_NO_REPORTS = "No reports.";
public static final String MESSAGE_NO_LICENSE = "No license.";
public static final String MESSAGE_NO_LOCATIONS = "No locations.";
public static final String MESSAGE_NO_PROFILE_FOUND = "No profile found.";
public static final String MESSAGE_NO_APP_FOUND = "No apps found.";
public static final String MESSAGE_NO_USER_LOGGED_IN = "No user logged in.";
private int code;
private String message;
private Object data;
private Object reference;
private Integer totalPage;
private Long size;
private Long totalSize;
public MidmResponse() {
}
public MidmResponse(int code, String msg) {
this.setCode(code);
this.setMessage(msg);
}
public MidmResponse(int code, String msg, Object data) {
this.setCode(code);
this.setMessage(msg);
this.setData(data);
}
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return this.data;
}
public DbObject getDataAsDbObject() {
Object data = this.getData();
return data == null ? new DbObject() : new DbObject((Map)data);
}
public void setData(Object data) {
if (data instanceof UpdateResult) {
UpdateResult result = (UpdateResult)data;
this.data = (new DbObject("matched", result.getMatchedCount())).append("modified", result.getModifiedCount());
} else {
this.data = data;
}
}
public Object getReference() {
return this.reference;
}
public DbObject getRefereceAsDbObject() {
Object data = this.getReference();
return data == null ? new DbObject() : new DbObject((Map)data);
}
public void setReference(Object reference) {
this.reference = reference;
}
public int getTotalPage() {
return this.totalPage;
}
public void setTotalPages(int totalPage) {
this.totalPage = totalPage;
}
public long getSize() {
return this.size;
}
public void setSize(long size) {
this.size = size;
}
public long getTotalSize() {
return this.totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public String toString() {
return McJsonUtils.toJson(this);
}
public TextMessage toTextMessage() {
return new TextMessage(this.toString());
}
public static String getSucceedResponse() {
return getResponse(200, "succeed");
}
public static String getSucceedResponse(List list) {
MidmResponse response = new MidmResponse(200, "succeed");
if (list != null) {
response.setData(list);
response.setSize((long)list.size());
}
return response.toString();
}
public static String getSucceedResponse(Page page) {
MidmResponse response = new MidmResponse(200, "succeed");
if (page != null) {
response.setData(page.getContent());
response.setTotalPages(page.getTotalPages());
response.setSize((long)page.getNumberOfElements());
response.setTotalSize(page.getTotalElements());
}
return response.toString();
}
public static String getSucceedResponse(Object data) {
return getResponse(200, "succeed", data);
}
public static String getFailedResponse() {
return getResponse(400, "failed");
}
public static String getResponse(int code, String msg) {
return (new MidmResponse(code, msg)).toString();
}
public static String getResponse(int code, String msg, Object data) {
return (new MidmResponse(code, msg, data)).toString();
}
public static String getResponse(Object object) {
return McJsonUtils.toJson(object);
}
}
@@ -0,0 +1,124 @@
package com.midm.model.news;
import com.midm.model.org.User;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class MessageLog {
@Id
private UUID uuid;
@DBRef
private NewsMessage message;
@DBRef
private User reader;
@Indexed
private UUID siteUuid;
@Indexed
private Date readDate;
@Indexed
private boolean isCheck;
@Indexed
private boolean isRead;
@Indexed
private Date checkDate;
@Indexed
private Date notified;
public MessageLog() {
}
public MessageLog(NewsMessage message, User reader, UUID siteUuid) {
this.uuid = UUID.randomUUID();
this.message = message;
this.reader = reader;
this.siteUuid = siteUuid;
this.isCheck = false;
this.notified = new Date();
}
public MessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) {
this.uuid = UUID.randomUUID();
this.message = message;
this.reader = new User(userUuid);
this.siteUuid = siteUuid;
this.isCheck = false;
this.notified = new Date();
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public NewsMessage getMessage() {
return this.message;
}
public void setMessage(NewsMessage message) {
this.message = message;
}
public User getReader() {
return this.reader;
}
public void setReader(User reader) {
this.reader = reader;
}
public boolean isCheck() {
return this.isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
public boolean isRead() {
return this.isRead;
}
public void setRead(boolean isRead) {
this.isRead = isRead;
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public Date getNotified() {
return this.notified;
}
public void setNotified(Date notified) {
this.notified = notified;
}
public Date getReadDate() {
return this.readDate;
}
public void setReadDate(Date readDate) {
this.readDate = readDate;
}
public Date getCheckDate() {
return this.checkDate;
}
public void setCheckDate(Date checkDate) {
this.checkDate = checkDate;
}
}
@@ -0,0 +1,306 @@
package com.midm.model.news;
import com.google.gson.internal.LinkedTreeMap;
import com.midm.model.device.Device;
import com.midm.model.message.MidmPacket;
import com.midm.model.message.MidmQuery;
import com.midm.model.org.User;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McDateTimeUtils;
import com.mitac.cell.utils.McEmailUtils;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class NewsMessage {
@Id
private UUID uuid;
@DBRef
private User writer;
private String category;
private String forWhat;
private DbObject reference;
private DbObject message;
private Boolean isUnremovable;
private Boolean isEnabled;
private Date sendSchedule;
private Date expiry;
@Transient
private boolean sendNow;
private Date created;
private Date updated;
public NewsMessage(Device device, String category) {
this.init();
this.category = "device_" + category;
this.reference.put("uuid", device.getUuid());
}
public NewsMessage(Device device) {
this.init();
this.reference.put("uuid", device.getUuid());
}
public NewsMessage(MidmPacket packet) {
MidmQuery query = packet.getQuery();
this.setUuid(query.getUuid());
this.created = query.getRegisteredAt();
this.updated = this.created;
String request = query.getRequest();
String command = query.getCommand();
this.category = String.format("%s_%s", request, command);
this.getReference().put("userUuid", query.getSenderUuid());
this.getReference().put("deviceUuid", packet.getRecieverUuid());
this.getReference().put("query", query.getQuery());
}
public NewsMessage() {
this.init();
}
public void init() {
this.uuid = UUID.randomUUID();
this.created = new Date();
this.updated = this.created;
}
public DbObject getMessage() {
if (this.message == null) {
this.message = new DbObject();
}
return this.message;
}
public DbObject getMessage(Locale locale) {
return this.getMessage(locale.toLanguageTag());
}
public DbObject getMessage(String languageTag) {
DbObject message = this.getMessage();
DbObject localedMessage = new DbObject();
if (message.get(languageTag) == null) {
message.put(languageTag, localedMessage);
} else if (message.get(languageTag) instanceof LinkedTreeMap) {
for(Map.Entry entry : ((LinkedTreeMap)message.get(languageTag)).entrySet()) {
localedMessage.append((String)entry.getKey(), entry.getValue());
}
message.put(languageTag, localedMessage);
} else if (message.get(languageTag) instanceof DbObject) {
localedMessage = (DbObject)message.get(languageTag);
message.put(languageTag, localedMessage);
} else if (message.get(languageTag) instanceof org.bson.Document) {
for(Map.Entry entry : ((org.bson.Document)message.get(languageTag)).entrySet()) {
localedMessage.append((String)entry.getKey(), entry.getValue());
}
message.put(languageTag, localedMessage);
}
return localedMessage;
}
public void setMessage(DbObject message) {
this.message = message;
}
public void setMessage(String title, String content) {
this.setTitle(title);
this.setContent(content);
}
public String getTitle() {
return this.getMessage("en-US").getString("title");
}
public String getSummary() {
return this.getMessage().getString("summary");
}
public boolean hasContent() {
return this.getMessage().containsKey("content");
}
public String getContent() {
return this.getMessage("en-US").getString("content");
}
public String getTitle(String locale) {
return this.getMessage(locale).getString("title");
}
public String getSummary(String locale) {
return this.getMessage(locale).getString("summary");
}
public boolean hasContent(String locale) {
return this.getMessage(locale).containsKey("content");
}
public String getContent(String locale) {
return this.getMessage(locale).getString("content");
}
public List getMailsTo() {
return McEmailUtils.parseMails(this.getMessage().getString("to"));
}
public void setMessage(String title, String content, String summary) {
this.setMessage(Locale.US.toLanguageTag(), title, content, summary);
}
public void setMessage(String languageTag, String title, String content, String summary) {
this.setTitle(languageTag, title);
this.setContent(languageTag, content);
this.setSummary(languageTag, summary);
}
public void setTitle(String title) {
this.setTitle(Locale.US.toLanguageTag(), title);
}
public void setContent(String content) {
this.setContent(Locale.US.toLanguageTag(), content);
}
public void setSummary(String summary) {
this.setSummary(Locale.US.toLanguageTag(), summary);
}
public void setTitle(String languageTag, String title) {
DbObject message = this.getMessage(languageTag);
message.put("title", title);
}
public void setContent(String languageTag, String content) {
DbObject message = this.getMessage(languageTag);
message.put("content", content);
}
public DbObject getReference() {
if (this.reference == null) {
this.reference = new DbObject();
}
return this.reference;
}
public void setReference(DbObject reference) {
this.reference = reference;
}
public void setSummary(String languageTag, String summary) {
DbObject message = this.getMessage(languageTag);
message.put("summary", summary);
}
public Boolean isUnremovable() {
return this.isUnremovable;
}
public void setIsUnremovable(Boolean isUnremovable) {
this.isUnremovable = isUnremovable;
}
public String getForWhat() {
return this.forWhat;
}
public void setForWhat(String forWhat) {
this.forWhat = forWhat;
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public User getWriter() {
return this.writer;
}
public void setWriter(User writer) {
this.writer = writer;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public Date getSendSchedule() {
return this.sendSchedule;
}
public void setSendSchedule(Date sendSchedule) {
this.sendSchedule = sendSchedule;
}
public boolean sendNow() {
return this.sendNow || this.sendSchedule == null || McDateTimeUtils.isSameDate(new DateTime(this.sendSchedule), DateTime.now());
}
public Date getExpiry() {
return this.expiry;
}
public void setExpiry(Date expiry) {
this.expiry = expiry;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return this.updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public Boolean getIsUnremovable() {
return this.isUnremovable;
}
public Boolean isEnabled() {
return this.isEnabled;
}
public void setIsEnabled(Boolean isEnabled) {
this.isEnabled = isEnabled;
}
public boolean isSendNow() {
return this.sendNow;
}
public void setSendNow(boolean sendNow) {
this.sendNow = sendNow;
}
public String toDateString(String dateString, String format) {
DateTime dateTime = new DateTime(dateString);
return McDateTimeUtils.toString(dateTime, format);
}
}
+383
View File
@@ -0,0 +1,383 @@
package com.midm.model.org;
import com.google.common.base.Strings;
import com.midm.model.GeneralProfile;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McUuidUtils;
import java.util.Date;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Site extends GeneralProfile {
public static final String MODEL_MIDM = "midm";
public static final String MODEL_MUST = "must";
@DBRef
private Site reseller;
@Indexed(
unique = true
)
private String idName;
@Transient
private Date latestVisit;
@Transient
private DbObject report;
public Site() {
this.setEnabled(false);
}
public Site(String model) {
this();
this.setModel(model);
}
public void init() {
this.setUuid(UUID.randomUUID());
DbObject notiSettings = new DbObject("sendEmail", true);
DbObject notiRoles = new DbObject("enabled", true);
notiRoles.append("roles", new DbObject("SUPERVISOR", true));
DbObject supportSettings = new DbObject("general", notiRoles);
supportSettings.append("maintenance", notiRoles).append("urgent", notiRoles);
notiSettings.append("support", supportSettings);
this.setSetting("noti", notiSettings);
this.setCreated(new Date());
}
public Site getReseller() {
return this.reseller;
}
public void setReseller(Site reseller) {
this.reseller = reseller;
}
public boolean isChild() {
return this.reseller != null;
}
public boolean canCustomize() {
return true;
}
public Object getDomainName() {
return this.getSetting("domainName");
}
public String getIdName() {
return this.idName;
}
public void setIdName(String idName) {
this.idName = idName;
}
public String getTitle() {
String siteName = (String)this.getSetting("theme", "siteName");
return Strings.isNullOrEmpty(siteName) ? this.getName() : siteName;
}
public boolean hasLogo() {
return this.getSettingAsBoolean("theme", "logo", false);
}
public DbObject getPlan() {
return this.getProfileCategory(new String[]{"plan"});
}
public String getPlanName() {
DbObject plan = this.getPlan();
return plan.getString("plan", "standard");
}
public String getShowPlanName() {
String planName = this.getPlanName();
return this.getShowPlanName(planName);
}
public String getShowPlanName(String planName) {
String name = "";
if (planName.equals("lite")) {
name = "Lite";
} else if (planName.equals("standard")) {
name = "Standard";
} else if (planName.equals("standardWithBatteryPro")) {
name = "Std + Batt Pro";
}
return name;
}
public void setPlan(DbObject plan) {
this.setProfile("plan", plan);
}
public void setPlan(String plan) {
if (!Strings.isNullOrEmpty(plan)) {
this.setProfile("plan", "plan", plan);
DbObject profilePlan = this.getProfile().getDbObject(new String[]{"plan"});
if (plan.equals("standard")) {
profilePlan.remove("features");
}
profilePlan.remove("upgradeStatus");
}
}
public String getUpgradeStatus() {
DbObject plan = this.getPlan();
return plan.getString("upgradeStatus");
}
public boolean isUpgradeRequested() {
return "processing".equals(this.getUpgradeStatus());
}
public String getUpgradeTargetPlan() {
DbObject plan = this.getPlan();
return plan.getString("targetPlan");
}
public String getModel() {
return (String)this.getProfile("model", "midm");
}
public void setModel(String model) {
this.setProfile("model", model);
}
public String getPhone() {
return (String)this.getProfile("phone");
}
public String getAddress() {
return (String)this.getProfile("address");
}
public String getCountry() {
return (String)this.getProfile("country");
}
public boolean isReseller() {
return (Boolean)this.getProfile("isReseller", false);
}
public void setIsReseller(boolean isReseller) {
this.setProfile("isReseller", isReseller);
}
public boolean limitRegisteredDeviceOnly() {
return this.getSettingAsBoolean("enrollment", "registeredOnly", false);
}
public Date getLatestVisit() {
return this.latestVisit;
}
public void setLatestVisit(Date latestVisit) {
this.latestVisit = latestVisit;
}
public DbObject getCredential() {
return this.getSettings().getDbObject(new String[]{"credential"});
}
public boolean isCredentialMatched(String credential) {
if (Strings.isNullOrEmpty(credential)) {
return false;
} else {
DbObject credentialSettings = this.getCredential();
if (credentialSettings != null && !credentialSettings.isEmpty()) {
String siteCredential = credentialSettings.getString("credential");
long cridentialExpiry = credentialSettings.getLong("expiry");
return (cridentialExpiry == -1L || cridentialExpiry > (new Date()).getTime()) && credential.equals(siteCredential);
} else {
return false;
}
}
}
public void setCredential(String credential) {
if (!Strings.isNullOrEmpty(credential)) {
DbObject value = new DbObject("credential", credential);
value.append("expiry", -1);
this.setSetting("credential", value);
} else {
this.getSettings().remove("credential");
}
}
public void renewCredential() {
String credential = McUuidUtils.toBase64String(UUID.randomUUID(), true);
this.setCredential(credential);
}
public DbObject getSettings() {
DbObject settings = super.getSettings();
if (settings.get("theme") == null) {
DbObject themeSettings = new DbObject();
themeSettings.put("skinColor", "steelblue");
themeSettings.put("logo", false);
settings.put("theme", themeSettings);
}
return settings;
}
public DbObject getReport() {
if (this.report == null) {
this.report = new DbObject();
}
return this.report;
}
public void setReport(DbObject report) {
this.report = report;
}
public void addReport(String key, Object value) {
this.getReport().put(key, value);
}
public boolean equals(Object obj) {
if (obj.hashCode() == this.hashCode()) {
return true;
} else if (obj instanceof Site) {
Site site = (Site)obj;
return this.getUuid().equals(site.getUuid());
} else if (obj instanceof SiteInfo) {
SiteInfo siteInfo = (SiteInfo)obj;
return this.getUuid().equals(siteInfo.getSiteUuid());
} else {
return obj instanceof UUID ? this.getUuid().equals((UUID)obj) : false;
}
}
public boolean isLite() {
return this.getPlanName().equals("lite");
}
public boolean isStandard() {
return this.getPlanName().equals("standard");
}
public boolean isStandardWithBatteryPro() {
return this.getPlanName().equals("standardWithBatteryPro");
}
public boolean isMust() {
return this.getModel().equals("must");
}
public void setMust(boolean isMust) {
this.setModel("must");
}
public boolean isFeatureAllowed(String subCategory, String item) {
return !this.isLite() ? true : this.getProfileAsBoolean("plan", "features", subCategory, item, false);
}
public DbObject getNotificationSettings() {
return this.getSettingsCategory(new String[]{"noti"});
}
public boolean notifyViaMail() {
return this.getNotificationSettings().getBoolean("sendEmail", false);
}
public void setNotifyViaMail(boolean viaMail) {
this.getNotificationSettings().put("sendEmail", viaMail);
}
public boolean notifyDeviceErrorMail() {
return this.getNotificationSettings().getBoolean("sendDeviceErrorEmail", false);
}
public void setNotifyDeviceErrorMail(boolean enable) {
this.getNotificationSettings().put("sendDeviceErrorEmail", enable);
}
public boolean notifyBatteryConditionMail() {
return this.getNotificationSettings().getBoolean("sendBatteryConditionEmail", false);
}
public void setNotifyBatteryConditionMail(boolean enable) {
this.getNotificationSettings().put("sendBatteryConditionEmail", enable);
}
public void setNotificationSettings(String category, String forWhat, boolean isEnabled) {
this.setNotificationSettings(category, forWhat, isEnabled, (Set)null);
}
public void setNotificationSettings(String category, String forWhat, boolean isEnabled, Set roles) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
settings.put("isEnabled", isEnabled);
if (roles == null) {
settings.remove("roles");
} else {
settings.put("roles", roles);
}
}
public void setNotificationSettings(String category, String forWhat, String key, String value) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
settings.put(key, value);
}
public String getDataUsage() {
return this.getSettingsCategory(new String[]{"report"}).getString("dataUsage", "none");
}
public boolean collectDataUsage() {
return !this.getDataUsage().equals("none");
}
public Set getMessageRoles(String category, String forWhat) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
if (settings.getBoolean("enabled")) {
Object value = settings.get("roles");
if (value instanceof Set) {
return (Set)value;
} else {
DbObject dt = (DbObject)value;
return dt.keySet();
}
} else {
return null;
}
}
public boolean hasTimeZone() {
return this.getSetting("general", "timeZone") != null;
}
public void setTimeZone(TimeZone timeZone) {
this.setSetting("general", "timeZone", timeZone.getID());
}
public TimeZone getTimeZone() {
Object timeZone = this.getSetting("general", "timeZone");
return timeZone != null ? TimeZone.getTimeZone((String)timeZone) : TimeZone.getDefault();
}
public String[] getIncludeApps() {
String installApps = this.getSettingsCategory(new String[]{"report"}).getString("installApps");
return Strings.isNullOrEmpty(installApps) ? null : installApps.split("[,;\\s]+");
}
public DbObject getCallbackSetting() {
return this.getSettingsCategory(new String[]{"callback"});
}
public String toString() {
return String.format("%s(%s):%s", this.getName(), this.getIdName(), this.getUuid());
}
}
@@ -0,0 +1,76 @@
package com.midm.model.org;
import com.midm.model.file.BaseFile;
import com.mitac.cell.io.McFile;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class SiteFile extends BaseFile {
private String category;
private String forWhat;
private Date requested;
private Date expiry;
private String siteName;
@DBRef
private User requestedFrom;
public SiteFile() {
}
public SiteFile(User requestedFrom, UUID fileUuid, McFile file) {
this.setUserUuid(requestedFrom);
this.setFileUuid(fileUuid);
this.setFileInfo(file);
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public User getRequestedFrom() {
return this.requestedFrom;
}
public void setRequestedFrom(User requestedFrom) {
this.requestedFrom = requestedFrom;
}
public Date getRequested() {
return this.requested;
}
public void setRequested(Date requested) {
this.requested = requested;
}
public Date getExpiry() {
return this.expiry;
}
public void setExpiry(Date expiry) {
this.expiry = expiry;
}
public String getSiteName() {
return this.siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getForWhat() {
return this.forWhat;
}
public void setForWhat(String forWhat) {
this.forWhat = forWhat;
}
}
@@ -0,0 +1,169 @@
package com.midm.model.org;
import com.google.common.base.Strings;
import com.mitac.cell.db.DbObject;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.springframework.data.mongodb.core.index.Indexed;
public class SiteInfo {
@Indexed
private UUID siteUuid;
private Set roles;
private UUID groupUuid;
protected DbObject settings;
private Boolean apiOnly;
private Date created;
private Date updated;
private boolean enabled;
public SiteInfo() {
this.setRoles(new HashSet());
this.setCreated(new Date());
this.setUpdated(new Date());
this.setEnabled(false);
}
public SiteInfo(UUID siteUuid) {
this();
this.setSiteUuid(siteUuid);
}
public UUID getSiteUuid() {
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
}
public Set getRoles() {
if (this.roles == null) {
this.roles = new HashSet();
}
return this.roles;
}
public boolean hasRole(String role) {
return this.isEnabled() && !this.getRoles().isEmpty() && this.getRoles().contains(role);
}
public boolean hasRole(Collection roles) {
if (this.isEnabled() && !this.getRoles().isEmpty()) {
for(String role : roles) {
if (this.getRoles().contains(role)) {
return true;
}
}
}
return false;
}
public void addRole(String role) {
role = UserRole.toRole(role);
if (!Strings.isNullOrEmpty(role)) {
this.getRoles().add(role);
}
}
public void setRoles(Set roles) {
if (roles != null && !roles.isEmpty()) {
for(String role : roles) {
role = UserRole.toRole(role);
if (!Strings.isNullOrEmpty(role) && !this.hasRole("SUPERVISOR")) {
if (role.equals("SUPERVISOR")) {
this.getRoles().clear();
this.getRoles().add(role);
} else {
this.getRoles().add(role);
}
}
}
} else {
this.roles = null;
}
}
public void clearRoles() {
this.getRoles().clear();
}
public UUID getGroupUuid() {
return this.groupUuid;
}
public void setGroupUuid(UUID groupUuid) {
this.groupUuid = groupUuid;
}
public boolean isApiOnly() {
return this.apiOnly != null && this.apiOnly;
}
public void setApiOnly(boolean apiOnly) {
this.apiOnly = apiOnly;
}
public DbObject getSettings() {
if (this.settings == null) {
this.settings = new DbObject();
}
return this.settings;
}
public void setSettings(DbObject settings) {
this.settings = settings;
}
public void setSetting(String key, Object value) {
this.getSettings().put(key, value);
}
public Object getSetting(String key) {
return this.getSettings().get(key);
}
public String getSettingAsString(String key) {
return this.getSettings().getString(key, (String)null);
}
public DbObject getPageSetting(String url) {
return this.getSettings().getDbObject(new String[]{"page", url});
}
public void setPageSetting(String url, String key, Object value) {
this.getPageSetting(url).put(key, value);
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return this.updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
@@ -0,0 +1,267 @@
package com.midm.model.org;
import com.google.common.base.Strings;
import com.midm.model.system.LicenseModel;
import com.mitac.cell.db.DbObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class SiteLicense {
@Id
private UUID uuid;
@DBRef
private Site site;
@DBRef
private Site childSite;
@Transient
private User writer;
@DBRef
private LicenseModel licenseModel;
private int amount;
private DbObject reference;
private String plan;
@Transient
private DbObject report;
private STATUS status;
private boolean enabled;
private Date updated;
private Date created;
public SiteLicense() {
this.plan = "standard";
this.status = SiteLicense.STATUS.UNKNOWN;
this.uuid = UUID.randomUUID();
this.enabled = true;
this.setCreated(new Date());
}
public SiteLicense(Site site) {
this();
this.setSite(site);
}
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public Site getSite() {
return this.site;
}
public void setSite(Site site) {
if (site.isChild()) {
this.site = site.getReseller();
this.childSite = site;
} else {
this.site = site;
}
}
public Site getChildSite() {
return this.childSite;
}
public boolean isForChildSite() {
return this.childSite != null;
}
public void setChildSite(Site reseller) {
this.childSite = reseller;
}
public User getWriter() {
return this.writer;
}
public void setWriter(User user) {
this.writer = user;
}
public String getPlan() {
return this.plan;
}
public void setPlan(String plan) {
this.plan = plan;
}
public boolean isLite() {
return "lite".equals(this.getPlan());
}
public LicenseModel getLicenseModel() {
return this.licenseModel;
}
public void setLicenseModel(LicenseModel licenseModel) {
if (this.isUpdated() && !this.licenseModel.getUuid().equals(licenseModel.getUuid())) {
this.addNote("License model changed: " + licenseModel.getName());
}
this.licenseModel = licenseModel;
}
public Character getType() {
return this.licenseModel.getType();
}
public Integer getPeriod() {
return this.licenseModel.getPeriod();
}
public int getAmount() {
return this.amount;
}
public void setAmount(int amount) {
if (this.isUpdated() && this.amount != amount) {
this.addNote("Amount changed: " + amount);
}
this.amount = amount;
}
public DbObject getReference() {
if (this.reference == null) {
this.reference = new DbObject();
}
return this.reference;
}
public void setReference(DbObject reference) {
this.reference = reference;
}
public String getPo() {
return this.getReference().getString("po", "");
}
public void setPo(String po) {
if (this.isUpdated() && !this.getPo().equals(po)) {
this.addNote(Strings.isNullOrEmpty(po) ? "PO has unset" : "PO changed: " + po);
}
this.getReference().put("po", po);
}
public String getDesc() {
return this.getReference().getString("desc", "");
}
public void setDesc(String desc) {
this.getReference().put("desc", desc);
}
public List getNotes() {
return this.getReference().getList("notes", DbObject.class);
}
public void addNote(STATUS status) {
if (this.isUpdated()) {
this.addNote("Status changed: " + status);
} else {
this.addNote(String.format("%s: %s, %,d licenses", status, this.licenseModel.getName(), this.amount));
}
}
public void addNote(String note) {
DbObject noteObj = new DbObject("name", this.writer.getName());
noteObj.append("email", this.writer.getEmail()).append("note", note).append("updated", this.updated);
List<DbObject> notes = this.getNotes();
if (notes == null) {
notes = new ArrayList();
this.getReference().append("notes", notes);
}
notes.add(noteObj);
}
public boolean getEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getUpdated() {
return this.updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
private boolean isUpdated() {
return !this.created.equals(this.updated);
}
public void updated() {
this.updated = new Date();
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
this.updated = created;
}
public DbObject getReport() {
if (this.report == null) {
this.report = new DbObject();
}
return this.report;
}
public void setReport(DbObject report) {
this.report = report;
}
public void setReport(String key, Object value) {
this.getReport().put(key, value);
}
public boolean isTrial() {
return this.getLicenseModel().isTrial();
}
public boolean isPerpetual() {
return this.getLicenseModel().isPerpetual();
}
public STATUS getStatus() {
return this.status;
}
public void setStatus(STATUS status) {
this.addNote(status);
this.status = status;
}
public static enum STATUS {
ORDERED,
PROCESSING,
CONFIRMED,
REJECTED,
CANCELED,
UNKNOWN;
}
}
@@ -0,0 +1,47 @@
package com.midm.model.org;
import com.mitac.cell.db.DbObject;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class SitePlan {
@Id
private UUID uuid;
private String model = "midm";
private DbObject plan;
private boolean isReseller = false;
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public DbObject getPlan() {
return this.plan;
}
public void setPlan(DbObject plan) {
this.plan = plan;
}
public boolean isReseller() {
return this.isReseller;
}
public void setReseller(boolean isReseller) {
this.isReseller = isReseller;
}
}
@@ -0,0 +1,92 @@
package com.midm.model.org;
import java.util.Date;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class SiteRequest {
@Id
private UUID uuid;
private String name;
private String email;
private String company;
private String title;
private String phone;
private String country;
private String industry;
private Date requestedAt;
public UUID getUuid() {
return this.uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getIndustry() {
return this.industry;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public Date getRequestedAt() {
return this.requestedAt;
}
public void setRequestedAt(Date requestedAt) {
this.requestedAt = requestedAt;
}
}
@@ -0,0 +1,31 @@
package com.midm.model.org;
public enum USER_PROPERTY {
email,
email_addr,
email_address,
role,
roles,
mail,
name,
password,
pwd,
group,
title,
position,
tel,
phone,
telephone,
mobile,
mobilephone,
mobile_phone,
unknown;
public static USER_PROPERTY get(String key) {
try {
return valueOf(key.trim().toLowerCase());
} catch (Exception var2) {
return unknown;
}
}
}
+687
View File
@@ -0,0 +1,687 @@
package com.midm.model.org;
import com.google.api.client.util.Strings;
import com.google.gson.annotations.Expose;
import com.midm.constant.LocaleConst;
import com.midm.model.GeneralProfile;
import com.midm.model.system.PolicyAgreement;
import com.mitac.cell.db.DbObject;
import com.mitac.cell.utils.McEmailUtils;
import com.mitac.cell.utils.McStringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.crypto.password.PasswordEncoder;
@Document
public class User extends GeneralProfile {
public static final int MAX_LOGIN_ATTEMPT = 5;
public static final int LOGIN_AFTER_MINUTES = 10;
@Indexed
private UUID siteUuid;
@Indexed
private String email;
@Expose(
serialize = false
)
private String password;
private List sites;
@Transient
private boolean isMultiSiteUser;
@Transient
private boolean isApiUser;
@Transient
private SiteInfo siteInfo;
private Set systemRoles;
@Transient
private UUID groupUuid;
protected Date activated;
@Transient
private Site site;
@Transient
private UserGroup userGroup;
public User() {
}
public User(UUID userUuid) {
this.setUuid(userUuid);
}
public User(String email) {
this();
this.setEmail(email);
}
public User(String email, String password) {
this(email);
this.setPassword(password);
}
public void init() {
super.init();
if (this.hasRole("SUPERVISOR") || this.hasSystemRole("SYSTEM_ADMIN")) {
this.setEnabled(true);
}
this.setActivated();
if (Strings.isNullOrEmpty(super.getName())) {
this.setName(this.getName());
}
}
public UUID getSiteUuid() {
if (this.siteUuid == null && !this.hasSystemRole()) {
List<SiteInfo> sites = this.getSites();
if (!sites.isEmpty()) {
this.setSiteUuid(((SiteInfo)sites.get(0)).getSiteUuid());
}
}
return this.siteUuid;
}
public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid;
SiteInfo siteInfo = this.getSiteInfo(siteUuid);
if (siteInfo != null) {
this.setRoles(siteInfo.getRoles());
}
}
public Site getSite() {
return this.site;
}
public void setSite(Site site) {
this.site = site;
}
public boolean isReseller() {
return this.site != null && this.site.isReseller();
}
public boolean isLite() {
return this.site != null && this.site.isLite();
}
public boolean isStandard() {
return this.site != null && this.site.isStandard();
}
public boolean isStandardWithBatteryPro() {
return this.site != null && this.site.isStandardWithBatteryPro();
}
public boolean isFeatureAllowed(String subCategory, String item) {
return this.isLite() ? this.site != null && this.site.isFeatureAllowed(subCategory, item) : true;
}
public boolean isFilesFeatureAllowed(String category, String key) {
return this.isFeatureAllowed(category, key) && (this.hasRole("SUPERVISOR") || this.hasRole("PROFILE_MANAGER"));
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
if (!Strings.isNullOrEmpty(email)) {
if (McEmailUtils.isValid(email)) {
this.email = email.toLowerCase();
}
if (Strings.isNullOrEmpty(super.getName())) {
this.setName(this.getName());
}
}
}
public String getPassword() {
return this.password;
}
public boolean setPassword(String password) {
this.password = password;
return !Strings.isNullOrEmpty(password) && password.length() >= 8 ? McStringUtils.hasUpperLowerDigit(password) : false;
}
public String getName() {
String name = super.getName();
if (Strings.isNullOrEmpty(name)) {
name = this.getEmail().substring(0, this.getEmail().indexOf("@"));
}
return name;
}
public void setSiteInfo(SiteInfo siteInfo) {
this.siteInfo = siteInfo;
}
public List getSites() {
if (this.sites == null) {
this.sites = new ArrayList();
}
return this.sites;
}
public List getSiteUuids() {
return this.sites != null && !this.sites.isEmpty() ? (List)this.sites.stream().map((item) -> item.getSiteUuid()).collect(Collectors.toList()) : null;
}
public boolean clearUndefinedSites() {
boolean hasChanges = false;
if (this.sites != null) {
Iterator<SiteInfo> it = this.sites.iterator();
while(it.hasNext()) {
SiteInfo site = (SiteInfo)it.next();
if (site.getSiteUuid() == null) {
it.remove();
hasChanges = true;
}
}
}
return hasChanges;
}
public void setSites(List sites) {
this.sites = sites;
}
public boolean isMultiSiteUser() {
return this.isMultiSiteUser;
}
public void setMultiSiteUser() {
this.isMultiSiteUser = this.getSites().size() > 1;
if (!this.isMultiSiteUser) {
this.isApiUser = this.isApiUser();
}
}
public SiteInfo getSiteInfo() {
return this.getSiteInfo(this.getSiteUuid());
}
public SiteInfo getSiteInfo(Site site) {
return this.getSiteInfo(site.getUuid());
}
public SiteInfo getSiteInfo(UUID siteUuid) {
if (siteUuid == null) {
return null;
} else {
for(SiteInfo siteInfo : this.getSites()) {
if (siteInfo.getSiteUuid() != null && siteInfo.getSiteUuid().equals(siteUuid)) {
return siteInfo;
}
}
return null;
}
}
public boolean isBelongedToSite(Site site) {
return this.isBelongedToSite(site.getUuid());
}
public boolean isBelongedToSite(UUID siteUuid) {
for(SiteInfo siteInfo : this.getSites()) {
if (siteInfo.getSiteUuid() != null && siteInfo.getSiteUuid().equals(siteUuid)) {
return true;
}
}
return false;
}
public boolean canHandle(UUID siteUuid, String... roles) {
SiteInfo info = this.getSiteInfo(siteUuid);
if (info != null) {
if (info.hasRole("SUPERVISOR")) {
return true;
}
for(String role : roles) {
if (info.hasRole(role)) {
return true;
}
}
}
return false;
}
public SiteInfo addSite(UUID siteUuid) {
if (siteUuid == null) {
return null;
} else {
if (!this.isBelongedToSite(siteUuid)) {
this.getSites().add(new SiteInfo(siteUuid));
}
if (this.getSiteUuid() == null) {
this.setSiteUuid(siteUuid);
}
SiteInfo siteInfo = this.getSiteInfo(siteUuid);
siteInfo.setEnabled(true);
return siteInfo;
}
}
public void removeSite(UUID siteUuid) {
if (siteUuid != null) {
SiteInfo existSite = null;
for(SiteInfo siteInfo : this.getSites()) {
if (siteInfo.getSiteUuid().equals(siteUuid)) {
existSite = siteInfo;
break;
}
}
if (existSite != null) {
this.getSites().remove(existSite);
}
if (this.getSites().isEmpty()) {
this.setSiteUuid((UUID)null);
this.setGroupUuid((UUID)null);
this.setLastSite((UUID)null);
} else {
if (siteUuid.equals(this.getSiteUuid())) {
this.setSiteUuid((UUID)null);
this.setGroupUuid((UUID)null);
}
if (siteUuid.equals(this.getLastSite())) {
this.setLastSite((UUID)null);
}
}
}
}
public Set getRoles() {
return this.getRolesBySite(this.getSiteUuid());
}
public Set getRoles(UUID siteUuid) {
return this.getRolesBySite(siteUuid);
}
public Set getRolesBySite(UUID siteUuid) {
SiteInfo info = this.getSiteInfo(siteUuid);
return (Set)(info != null ? this.getSiteInfo(siteUuid).getRoles() : new HashSet());
}
public void setRoles(Set roles) {
SiteInfo info = this.getSiteInfo(this.getSiteUuid());
if (info != null) {
this.getSiteInfo(this.getSiteUuid()).setRoles(roles);
}
}
public void addRoleToSite(String role, UUID siteUuid) {
role = UserRole.toRole(role);
if (role != null) {
if (role.equals("SUPERVISOR")) {
this.getRoles(siteUuid).clear();
}
this.getRolesBySite(siteUuid).add(role);
}
}
public void removeRole(String role) {
this.getRoles().remove(role);
}
public void removeRole(UUID siteUuid, String role) {
SiteInfo siteInfo = this.getSiteInfo(siteUuid);
if (siteInfo != null) {
siteInfo.getRoles().remove(role);
}
}
public Set getSystemRoles() {
if (this.systemRoles == null) {
this.systemRoles = new HashSet();
}
return this.systemRoles;
}
public void setSystemRoles(Set systemRoles) {
this.systemRoles = systemRoles;
}
public void addSystemRole(String role) {
this.getSystemRoles().add(role);
}
public void removeSystemRole(String role) {
this.getSystemRoles().remove(role);
}
public boolean hasSystemRole() {
return !this.getSystemRoles().isEmpty();
}
public boolean hasSystemRole(String role) {
return this.getSystemRoles().contains(role);
}
public boolean hasRole(String role) {
return this.hasRole(this.getSiteUuid(), role);
}
public boolean hasRole(UUID siteUuid, String role) {
SiteInfo site = this.getSiteInfo(siteUuid);
return site != null ? site.hasRole(role) : false;
}
public boolean isSupervisor() {
return this.hasRole("SUPERVISOR");
}
public boolean isSystemUser() {
return !this.getSystemRoles().isEmpty();
}
public boolean isSystemAdmin() {
return this.getSystemRoles().contains("SYSTEM_ADMIN");
}
public UUID getGroupUuid() {
return this.groupUuid;
}
public void setGroupUuid(UUID groupUuid) {
this.groupUuid = groupUuid;
}
public Date getActivated() {
return this.activated;
}
public void setActivated(Date activated) {
this.activated = activated;
}
public void setActivated() {
this.activated = new Date();
this.enabled = true;
}
public boolean isActivated() {
return true;
}
public boolean isAvailable() {
return this.getEnabled() && this.isActivated();
}
public String getEmailAddress() {
String EMAIL_FORMAT = "%s<%s>";
String name = this.getName();
if (McStringUtils.isNullOrEmpty(this.email)) {
return null;
} else {
return McStringUtils.isNullOrEmpty(name) ? this.email : String.format("%s<%s>", name, this.email);
}
}
public UserGroup getUserGroup() {
return this.userGroup;
}
public void setUserGroup(UserGroup userGroup) {
this.userGroup = userGroup;
if (userGroup != null) {
SiteInfo siteInfo = this.getSiteInfo(userGroup.getSiteUuid());
if (siteInfo != null) {
siteInfo.setGroupUuid(userGroup.getUuid());
} else {
this.userGroup = null;
}
}
}
public void encodePassword(PasswordEncoder encoder, String password) {
this.password = encoder.encode(password);
}
public void encodePassword(PasswordEncoder encoder) {
this.password = encoder.encode(this.password);
}
public boolean canRegister() {
return !McStringUtils.isNullOrEmpty(this.getEmail()) && !McStringUtils.isNullOrEmpty(this.getPassword());
}
public List getAuthorities() {
return UserRole.getAuthorities(this.getRoles());
}
public String getTheme() {
String theme = "default";
if (this.site != null) {
String model = this.site.getModel();
if (!Strings.isNullOrEmpty(model) && !model.equals("midm")) {
theme = model;
}
}
return theme;
}
public String getLocale() {
String locale = this.getSettingAsString("language");
return McStringUtils.isNullOrEmpty(locale) ? LocaleConst.DEFAULT_LOCALE.toLanguageTag() : locale;
}
public void setLocale(Locale locale) {
this.setLocale(locale.toLanguageTag());
}
public void setLocale(String locale) {
this.setSetting("language", locale);
}
public boolean isSameLocale(Locale locale) {
return this.isSameLocale(locale.toLanguageTag());
}
public boolean isSameLocale(String localeTag) {
return this.getLocale().equals(localeTag);
}
public boolean keepSignIn() {
return this.getSettingAsBoolean("keepSignIn");
}
public UUID getLastSite() {
UUID uuid = this.getSettingAsUuid("lastSite");
if (uuid == null && this.sites != null && !this.sites.isEmpty() && !this.hasSystemRole()) {
uuid = ((SiteInfo)this.sites.get(0)).getSiteUuid();
this.setLastSite(uuid);
}
return uuid;
}
public void setLastSite(UUID uuid) {
this.setSetting("lastSite", uuid);
}
public String getLastPage() {
SiteInfo siteInfo = this.getSiteInfo(this.siteUuid);
return siteInfo == null ? this.getSettingAsString("lastPage") : siteInfo.getSettingAsString("lastPage");
}
public List getDashboardSettings() {
SiteInfo siteInfo = this.getSiteInfo(this.siteUuid);
if (siteInfo != null) {
Object settings = siteInfo.getSetting("dashboard");
if (settings != null && settings instanceof List) {
return (List)settings;
}
}
return new ArrayList();
}
public DbObject getReportSettings() {
SiteInfo siteInfo = this.getSiteInfo(this.siteUuid);
return siteInfo != null ? siteInfo.getSettings().getDbObject(new String[]{"report"}) : new DbObject();
}
public void setDashboardSettings(List dashboard) {
SiteInfo siteInfo = this.getSiteInfo(this.siteUuid);
if (siteInfo != null) {
siteInfo.setSetting("dashboard", dashboard);
}
}
public void setLastPage(String url) {
SiteInfo siteInfo = this.getSiteInfo(this.siteUuid);
if (siteInfo != null) {
siteInfo.setSetting("lastPage", url);
}
}
public DbObject getPageSettings(String pageUrl) {
Object settings = this.getSetting("page", pageUrl);
DbObject var3;
if (settings == null) {
var3 = new DbObject();
} else {
if (settings instanceof DbObject) {
return (DbObject)settings;
}
if (settings instanceof Map) {
var3 = new DbObject((Map)settings);
} else {
var3 = new DbObject();
}
}
this.setSetting("page", pageUrl, var3);
return var3;
}
public Object getPageSetting(String pageUrl, String key) {
return this.getPageSettings(pageUrl).get(key);
}
public void setPageSetting(String pageUrl, String key, Object value) {
if (value == null) {
this.getPageSettings(pageUrl).remove(key);
} else {
this.getPageSettings(pageUrl).put(key, value);
}
}
public void updateProfile(DbObject newProfile) {
DbObject profile = this.getProfile();
newProfile.forEach((key, value) -> {
if (!key.equals("eula") && !key.equals("ip")) {
profile.put(key, value);
}
});
}
public void setEula(PolicyAgreement agreement) {
this.setProfile("eula", (new DbObject("uuid", agreement.getUuid().toString())).append("version", agreement.getVersion()).append("acceptDate", new Date()));
}
public void setEula(String value) {
Object object = McStringUtils.isNullOrEmpty(value) ? new DbObject() : DbObject.parse(value);
this.setProfile("eula", object);
}
public String getMfaMethod() {
return this.getSettingAsString("mfa");
}
public boolean isEulaAgreed() {
return this.isApiUser() || this.getCategoryProfile("eula", "acceptDate") != null;
}
public boolean isApiUser() {
SiteInfo siteInfo = this.getSiteInfo();
return siteInfo != null && siteInfo.isApiOnly();
}
public boolean equals(Object user) {
if (user == null) {
return false;
} else if (user instanceof User) {
return this.getEmail().equalsIgnoreCase(((User)user).getEmail());
} else if (user instanceof String) {
return this.getEmail().equals((String)user);
} else {
return user instanceof UUID ? user.equals(this.getUuid()) : super.equals(user);
}
}
public void setProfileOnly() {
this.siteUuid = null;
this.sites = null;
this.systemRoles = null;
this.activated = null;
this.settings = null;
this.created = null;
this.updated = null;
this.getProfile().remove("eula");
}
public DbObject getLoginAttempt() {
return this.getSettings().getDbObject(new String[]{"loginAttempt"});
}
public void loginFailed() {
DbObject loginAttempt = this.getLoginAttempt();
loginAttempt.put("attemptAt", new Date());
int count = loginAttempt.getInteger("count", 0) + 1;
loginAttempt.put("count", count % 6);
this.setSetting("loginAttempt", loginAttempt);
}
public void resetLoginAttempt() {
this.getSettings().remove("loginAttempt");
}
public String toString() {
return this.getEmail();
}
}
Loaded 100 of 3045 files, more files were not shown because too many files have changed in this diff. Show more