Commit be8bc544 by 284718418@qq.com

考勤机代码

parents
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?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.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl8timer.kqj</groupId>
<artifactId>yl8timer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<profiles>
<profile>
<id>dev</id>
<properties>
<environment>dev</environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<environment>test</environment>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<environment>pro</environment>
</properties>
</profile>
</profiles>
<properties>
<java.version>1.8</java.version>
<tomcat.version>8.5.50</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加MySQL依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加JDBC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<finalName>8timer-record</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
package com.yl8timer.kqj.yl8timer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
@RestController
@EnableScheduling
@MapperScan("com.yl8timer.kqj.yl8timer.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory createEmbeddedServletContainerFactory() {
TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
tomcatFactory.addConnectorCustomizers(connector -> {
// AbstractProtocol protocol = (AbstractProtocol)
// connector.getProtocolHandler();
// protocol.setSendReasonPhrase(true);
// connector.setPort(8087);
connector.setProperty("sendReasonPhrase", "true");
});
return tomcatFactory;
}
@Value("${spring.profiles.active}")
private String env;
@GetMapping(value = "/t")
public String testEnv() {
return env;
}
}
package com.yl8timer.kqj.yl8timer.ctrl;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkData;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsResponse;
@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class CleaningIntervalController {
@Value("${config.cleaning-interval}")
private Integer cleaninginterval;
/**
* 每天凌晨4点 删除前30天数据
*/
@Scheduled(cron = "0 0 4 * * ?")//每天凌晨4点
public void datadump() {
String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString();//
String front = requires_extra_times(str,-cleaninginterval,3,2);//前30天的开头
FkData.builder().build().delete(new QueryWrapper<FkData>().lambda().le(FkData::getIoTime, front));
FkHsRequest.builder().build().delete(new QueryWrapper<FkHsRequest>().lambda().le(FkHsRequest::getTime, front));
FkHsResponse.builder().build().delete(new QueryWrapper<FkHsResponse>().lambda().le(FkHsResponse::getTime, front));
}
/**
* @param timeStr 修改的时间
* @param num 修改数字
* @param numtime
* @return 1:增加一年、2:增加一天、3:减10天、4:增加一个月
*/
public static String requires_extra_times(String timeStr, int num,int numtime,int daft) {
DateFormat df;
if(daft == 1) {
df = new SimpleDateFormat("yyyy-MM-dd");
}else {
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);// 设置起时间
if(numtime == 1) {
cal.add(Calendar.YEAR, num);// 增加一年
}else if(numtime == 2) {
cal.add(Calendar.DATE, num);//增加一天
}else if(numtime == 3) {
cal.add(Calendar.DATE, num);//减10天
}else if(numtime == 4){
cal.add(Calendar.MONTH, num);//增加一个月
}else if(numtime == 5) {
cal.add(Calendar.HOUR, num);
}
return df.format(cal.getTime());
}
}
/**
* <p>Title: TestController.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.ctrl;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkDev;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsResponse;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTask;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTaskRelation;
import com.yl8timer.kqj.yl8timer.tools.Constant;
import com.yl8timer.kqj.yl8timer.tools.HSTools;
import com.yl8timer.kqj.yl8timer.tools.LogUtil;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
import com.yl8timer.kqj.yl8timer.tools.Result;
import com.yl8timer.kqj.yl8timer.tools.ResultUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
/**
* <p>
* Title: TestController.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@RestController
@RequestMapping(value = "/", produces = { "application/json" })
public class FkController {
@Autowired
private HSTools hsTools;
// 绑定考勤机
@PostMapping("/addDev")
public Result<FkDev> addDev(@RequestParam Integer orgCode, @RequestParam String devId) {
FkDev fkDev0 = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev0 != null) {
return ResultUtil.success();
}
FkDev fkDev = new FkDev();
fkDev.setOrgCode(orgCode);
fkDev.setDevId(devId);
fkDev.setCreatedTime(new Date());
fkDev.setUpdateTime(new Date());
fkDev.insert();
return ResultUtil.data(fkDev, "绑定成功");
}
// 向考勤机同步写入用户的注册数据和名称
@PostMapping("/addUser")
public Result<Object> addUser(@RequestParam String devId, @RequestParam String jsonStr) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId)); // 判断设备厂家
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
boolean result = false;
try {
result = hsTools.setUser(devId, jsonStr); // 设置用户信息
} catch (Exception e) {
return ResultUtil.error("添加失败,请确认考勤机绑定状态");
}
if (result == false)
return ResultUtil.error("添加失败");
return ResultUtil.data("添加成功");
} else
// TODO 预留其他考勤机设备
return ResultUtil.error("添加失败,请联系管理员");
}
// 添加、修改用户姓名
@PostMapping("/addUserName")
public Result<Object> addUserName(@RequestParam String devId, @RequestParam String userId,
@RequestParam String userName) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
boolean result = false;
try {
result = hsTools.setUserName(devId, userId, userName);
} catch (Exception e) {
return ResultUtil.error("添加失败,请确认考勤机绑定状态");
}
if (result == false)
return ResultUtil.data("添加失败");
return ResultUtil.data("添加成功");
} else
return ResultUtil.data("添加失败,请联系管理员");
}
// 添加、修改用户权限
@PostMapping("/addUserPrivilege")
public Result<Object> addUserPrivilege(@RequestParam String devId, @RequestParam String userId,
@RequestParam(required = false) Integer privilege) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
boolean result = false;
try {
result = hsTools.addUserPrivilege(devId, userId, privilege);
} catch (Exception e) {
return ResultUtil.error("添加失败,请确认考勤机绑定状态");
}
if (result == false)
return ResultUtil.data("添加失败");
return ResultUtil.data("添加成功");
} else
return ResultUtil.data("添加失败,请联系管理员");
}
// 同步考勤机时间
@PostMapping("/setTime")
public Result<String> setTime(@RequestParam String devId) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
boolean result = false;
try {
result = hsTools.setTime(devId);
} catch (Exception e) {
return ResultUtil.error("添加失败,请确认考勤机绑定状态");
}
if (result == false)
return ResultUtil.data("添加失败");
return ResultUtil.data("同步成功");
} else
return ResultUtil.data("设置失败,请联系管理员");
}
// 删除考勤机用户
@PostMapping("/deleteUser")
public Result<String> deleteUser(@RequestParam String devId, @RequestParam String userId) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
boolean result = false;
try {
result = hsTools.setDeleteUser(devId, userId);
} catch (Exception e) {
return ResultUtil.error("删除失败,请确认考勤机绑定状态");
}
if (result == false)
return ResultUtil.data("删除失败");
return ResultUtil.data("删除成功");
} else
return ResultUtil.data("删除失败,请联系管理员");
}
// 获取考勤机live信息
@PostMapping("/getDevInfo")
public Result<Integer> getDevInfo(@RequestParam String devId) {
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev == null)
return ResultUtil.data(0, "考勤机不存在");
long bet = DateUtil.between(fkDev.getUpdateTime(), new Date(), DateUnit.MINUTE);
if (bet >= 5) // 超过5分钟没有响应则判断为不在线
return ResultUtil.data(2, "考勤机离线");
return ResultUtil.data(1, "考勤机在线");
}
// 获取用户信息
@PostMapping("/getUserInfo")
public Result<String> getUserInfo(@RequestParam String devId, @RequestParam String userId) {
// 判断机器类型
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺 2-浩顺3代
String transId = hsTools.getUserInfo(devId, userId);
if (transId == null)
return ResultUtil.error("获取失败");
return ResultUtil.data(transId, "获取成功");
} else {
return ResultUtil.data("获取失败,请联系管理员");
}
}
// 获取用户信息s
@PostMapping("/getUsersInfo")
public Result<List<String>> getUsersInfo(@RequestParam String devId, @RequestParam List<String> userIds) {
// 判断机器类型
FkDev fkDev = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, devId));
String transId = null;
List<String> transIds = new ArrayList<String>();
if (fkDev != null && (fkDev.getOrgCode() == 1 || fkDev.getOrgCode() == 2)) { // 1-浩顺
for (String userId : userIds) {
transId = hsTools.getUserInfo(devId, userId);
transIds.add(transId);
}
return ResultUtil.data(transIds, "获取成功,请等待设备响应");
} else {
return ResultUtil.error("获取失败,请联系管理员");
}
}
// 获取任务状态
@GetMapping("/getTaskInfo")
public Result<JSONObject> getTaskInfo(@RequestParam Integer taskId) {
FkTask fkTask = FkTask.builder().id(taskId).build().selectById();
JSONObject json = new JSONObject();
if (fkTask == null) {
return ResultUtil.error("任务不存在");
}
Date beginDate = fkTask.getCreatedTime();
Date endDate = fkTask.getSuccessTime();
if (endDate != null) {
Long time = endDate.getTime() - beginDate.getTime();
json.put("executionTime", time);
}
Integer result = fkTask.getStatus();
json.put("id", taskId);
if (result == 1) {
json.put("result", "任务执行中");
json.put("resultCode", 1);
getUserList(json, taskId);
} else if (result == 2) {
json.put("result", "任务已完成");
json.put("resultCode", 2);
getUserList(json, taskId);
} else if (result == 3) {
json.put("result", "任务超时失败");
json.put("resultCode", 3);
getUserList(json, taskId);
} else {
json.put("result", "任务不存在或未开始");
json.put("resultCode", 0);
}
return ResultUtil.data(json);
}
private void getUserList(JSONObject json, Integer taskId) {
List<FkTaskRelation> fkTaskRelations = FkTaskRelation.builder().build()
.selectList(new LambdaQueryWrapper<FkTaskRelation>().eq(FkTaskRelation::getTaskId, taskId));
List<JSONObject> list = new LinkedList<JSONObject>();
for (FkTaskRelation fkTaskRelation : fkTaskRelations) {
JSONObject json3 = new JSONObject();
json3.put("userId", fkTaskRelation.getUserId());
String getTransId = fkTaskRelation.getGetTransId();
if (getTransId != null) {
FkHsRequest get = FkHsRequest.builder().id(Integer.parseInt(getTransId)).build().selectById();
json3.put("getStatus", get.getStatus());
} else {
json3.put("getStatus", "null");
}
String setTransId = fkTaskRelation.getSetTransId();
if (setTransId != null) {
FkHsRequest set = FkHsRequest.builder().id(Integer.parseInt(setTransId)).build().selectById();
json3.put("setStatus", set.getStatus());
} else {
json3.put("setStatus", "null");
}
list.add(json3);
}
json.put("userList", list);
}
// // 同步考勤机数据 TODO
// @Transactional
// @PostMapping("/setUserInfoOntime")
// public Result<String> setUserInfoOntime(@RequestParam String oldDevId, @RequestParam String newDevId,
// @RequestParam List<String> ids) {
// // 判断机器类型
// FkDev fkDev1 = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, oldDevId));
// FkDev fkDev2 = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, newDevId));
// if (fkDev1 == null || fkDev2 == null)
// return ResultUtil.error("请先绑定考勤机");
// Integer code1 = fkDev1.getOrgCode();
// Integer code2 = fkDev2.getOrgCode();
// boolean result = false;
// if (code1 != code2)
// return ResultUtil.error("不同品牌考勤机无法同步用户数据");
// if ((code1 == 1 && code2 == 1) || (code1 == 2 && code2 == 2)) { // 1-浩顺 2-浩顺3代
// try {
// for (String id : ids) {
// String transId = hsTools.getUserInfo(oldDevId, id);
//
// byte[] str = FkHsResponse.builder().build()
// .selectOne(new LambdaQueryWrapper<FkHsResponse>().eq(FkHsResponse::getTransId, transId))
// .getTotalByte();
//
// result = hsTools.setUserInfo(newDevId, str);
// }
// } catch (Exception e) {
// return ResultUtil.error("请确认考勤机绑定状态");
// }
//
// if (result != true)
// return ResultUtil.error("获取失败");
// return ResultUtil.data("获取成功");
// } else {
// return ResultUtil.data("获取失败,请联系管理员");
// }
//
// }
@PostMapping(value = "/") // 考勤机http请求地址
public void getData() throws UnsupportedEncodingException {
attendanceMachineRequestPath(); // 考勤机http请求内容
}
public void attendanceMachineRequestPath() throws UnsupportedEncodingException {
String sRequestCode = "";
String sTransId = "";
byte[] bytEmpty = new byte[0];
final String csFuncName = "Page_Load";
hsTools.request.setCharacterEncoding("UTF-8");
hsTools.response.setCharacterEncoding("UTF-8");
hsTools.response.setHeader("content-type", "text/html;charset=UTF-8");
// 是否打印
hsTools.log = LogUtil.getInstance(true);
try {
sRequestCode = hsTools.request.getHeader("request_code");
if (!MyUtil.isValidEngDigitString(sRequestCode)) {
hsTools.log.e(csFuncName, "Invalid request_code : " + sRequestCode);
return;
}
sTransId = hsTools.request.getHeader("trans_id");
if (sTransId == null)
sTransId = "";
hsTools.log.i(csFuncName, "1 - request_code : " + sRequestCode + " ,trans_id : " + sTransId);
String sDevId = hsTools.request.getHeader("dev_id");
if (!MyUtil.isValidEngDigitString(sDevId)) {
hsTools.log.e(csFuncName, "error - Invalid dev_id : " + sDevId);
return;
}
int lenContent = hsTools.GetRequestStreamBytes(hsTools.request);
if (lenContent < 0) {
hsTools.log.e(csFuncName, "2.1" + lenContent);
return;
}
// 块序号
int nBlkNo = 0;
if (hsTools.request.getHeader("blk_no") != null)
nBlkNo = Integer.parseInt(hsTools.request.getHeader("blk_no"));
int vRet;
if (nBlkNo > 0) {
vRet = hsTools.AddBlockData(sDevId, nBlkNo, hsTools.bytRequestBin);
if (vRet != 0) {
hsTools.log.e(csFuncName, "3.0 - error - AddBlockData:" + vRet);
hsTools.SendResponseToClient("ERROR_ADD_BLOCK_DATA", sTransId, "", bytEmpty, hsTools.response);
return;
}
hsTools.log.i(csFuncName, "3.1");
hsTools.SendResponseToClient("OK", sTransId, "", bytEmpty, hsTools.response);
return;
} else if (nBlkNo < 0) {
hsTools.SendResponseToClient("ERROR_INVLAID_BLOCK_NO", sTransId, "", bytEmpty, hsTools.response);
return;
} else {
hsTools.GetBlockDataAndRemove(sDevId);
hsTools.bytRequestTotal = hsTools.ConcateByteArray(hsTools.bytRequestTotal, hsTools.bytRequestBin);
}
FkHsResponse fkHsResponse = new FkHsResponse();
fkHsResponse.setCommand(sRequestCode);
fkHsResponse.setDevId(sDevId);
fkHsResponse.setTime(new Date());
String byteStr = new String();
// System.err.println("byteStr:" + byteStr);
// System.err.println("byteStr:"+byteStr);
// System.err.println("nBlkNo:"+nBlkNo);
fkHsResponse.setTotalByte(hsTools.bytRequestTotal);
// if (sRequestCode != Constant.REQ_CODE_RECV_CMD) {
fkHsResponse.setTransId(sTransId);
fkHsResponse.insert();
// }
switch (sRequestCode) {
case Constant.REQ_CODE_RECV_CMD:
hsTools.RemoveOldBlockStream();
hsTools.OnReceiveCmd(sDevId, sTransId, hsTools.bytRequestTotal, hsTools.response);
break;
case Constant.REQ_CODE_SEND_CMD_RESULT:
hsTools.OnSendCmdResult(sDevId, sTransId, hsTools.bytRequestTotal, hsTools.response, hsTools.request);
break;
case Constant.REQ_CODE_REALTIME_GLOG: // 实时指纹打卡
hsTools.OnRealtimeGLog(sDevId, hsTools.bytRequestTotal, hsTools.response, hsTools.request);
break;
case Constant.REQ_CODE_REALTIME_ENROLL: // 新添加指纹
hsTools.OnRealtimeEnrollData(sDevId, hsTools.bytRequestTotal, hsTools.response, hsTools.request);
break;
case "":
break;
default:
hsTools.SendResponseToClient("OK", sTransId, "", bytEmpty, hsTools.response);
break;
}
} catch (Exception e) {
hsTools.log.e("Page_Load---->" + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
package com.yl8timer.kqj.yl8timer.ctrl;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
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.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.yl8timer.kqj.yl8timer.entity.Command;
import com.yl8timer.kqj.yl8timer.entity.Device;
import com.yl8timer.kqj.yl8timer.entity.EnrollData;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS100_GLog;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS100_UserIdInfo;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS101_GLog;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS101_UserIdInfo;
import com.yl8timer.kqj.yl8timer.entity.FKWebTransBlockData;
import com.yl8timer.kqj.yl8timer.tools.Constant;
import com.yl8timer.kqj.yl8timer.tools.LogUtil;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
@RestController
public class KqjController {
private byte[] bytRequestBin;
private byte[] bytRequestTotal;
private LogUtil log;
private String serverUrl = "http://192.168.4.222:8089";// 对应8小时 考勤接口
private String defPath = "E:\\ylwork\\zwj\\f";
private String defimgPath = "E:\\ylwork\\zwjimg\\";
@Autowired
private HttpServletResponse response;
@Autowired
private HttpServletRequest request;
// @PostMapping(value = "/cmd")
// public void cmd(@RequestParam String cmd, @RequestParam String devid, @RequestParam String json) {
// Device dev = Device.getDevice(devid);
// if (dev == null)
// return;
// switch (cmd) {
// case Command.SET_TIME:
// dev.addCmd(Command.SET_TIME, "{\"time\":\"" + MyUtil.GetFKTimeString14(new Date()) + "\"}");
// break;
// case Command.SET_USER_INFO:
// JSONObject user = new JSONObject(json);
// String username = user.getStr("user_name");
// if (username == null || "".equals(username)) {
// dev.addCmd(cmd, json);
// return;
// }
// String userid = user.getStr("user_id");
// try {
// File f = new File(defPath + userid);
// if (f.exists()) {
// FileInputStream fis = new FileInputStream(f);
// ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
// byte[] bbb = new byte[1000];
// int n;
// while ((n = fis.read(bbb)) != -1) {
// bos.write(bbb, 0, n);
// }
// fis.close();
// byte[] bys = bos.toByteArray();
// bos.close();
// dev.addCmd(Command.SET_USER_INFO, bys);
// } else {
// dev.addCmd(cmd, json);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// break;
// default:
// dev.addCmd(cmd, json);
// break;
// }
// }
//
// //// 测试接口
// @GetMapping(value = "/cmd/{cmd}")
// public void cmd(@PathVariable Integer cmd) {
// Device dev = Device.getDevice("E468648507402D2B");
// if (dev == null)
// return;
// JSONObject vResultJson = new JSONObject();
// switch (cmd) {
// case 1: {
// // SET_ENROLL_DATA
// // SET_USER_INFO
// // vResultJson.put("user_id", "002");
// // vResultJson.put("user_name", "李桂强");
// // vResultJson.put("user_privilege", "USER");
// // dev.addCmd("SET_USER_INFO", vResultJson.toString());
//
// vResultJson.put("user_id", "600119");
// vResultJson.put("user_privilege", "MANAGE");
// dev.addCmd("SET_USER_INFO", vResultJson.toString());
//
// // if (ConvertEnrollDataInCmdParamBin(log, dev, cmd1))
// // dev.addCmd(cmd1);
// break;
// }
// case 2:
// vResultJson.put("user_id", "600120");
// String sFinal = vResultJson.toString();
// dev.addCmd("DELETE_USER", vResultJson.toString());
// break;
// case 3:
// // 更新时间
// dev.addCmd("SET_TIME", "{\"time\":\"" + MyUtil.GetFKTimeString14(new Date()) + "\"}");
//
// break;
// case 5:
// break;
// case 4:
// try {
// FileInputStream fis = new FileInputStream(new File(defPath + "600119"));
// ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
// byte[] bbb = new byte[1000];
// int n;
// while ((n = fis.read(bbb)) != -1) {
// bos.write(bbb, 0, n);
// }
// fis.close();
// byte[] bys = bos.toByteArray();
// bos.close();
// dev.addCmd("SET_USER_INFO", bys);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// break;
// // // 更新固件
// // if (MakeUpdateFirmwareCmdParamBin(log, dev.getDevId(), dev.getFk_info(), cmd)
// // == false) {
// // cmd.setBytCmd(new byte[0]);
// // cmd.setsResponse("ERROR_GET_PARAM");
// // return;
// // }
// }
// }
// 设置指纹,用户
private boolean ConvertEnrollDataInCmdParamBin(LogUtil log, Device dev, Command cmd) {
final String csFuncName = "ConvertEnrollDataInCmdParamBin";
log.i(csFuncName, "1 - ");
try {
JSONObject jobjDevInfo = new JSONObject(dev.getFk_info());
int DstFpDataVer = jobjDevInfo.getInt("fp_data_ver");
log.i(csFuncName, "1 - 1 - FpDataVer=" + DstFpDataVer);
// 机器采用的指纹数据版本
if (DstFpDataVer < 1 || DstFpDataVer > 10000) {
// 版本错误
return false;
}
Command innerCmd = new Command();
String sCmdParam = GetStringFromBSCommBuffer(cmd.getBytCmd());
if (sCmdParam.length() == 0) {
log.e(csFuncName, "2 - 1.1 - ");
return false;
}
JSONObject jobjCmdParam = new JSONObject(sCmdParam);
// 远程进入 录入页面
if (cmd.getCmdCode().equals("SET_ENROLL_DATA")) {
log.i(csFuncName, "2 - 2 - ");
int bkNo = jobjCmdParam.getInt("backup_number");
if (bkNo > 9) {
log.i(csFuncName, "2 - 2.1 - ");
return true;
}
log.i(csFuncName, "2 - 3 - ");
byte[] bytFpData = GetBinDataFromBSCommBinData(1, cmd.getBytCmd());
if (bytFpData.length == 0) {
log.e(csFuncName, "2 - 3.1 - ");
return false;
}
log.i(csFuncName, "2 - 4 - DstFpDataVer :" + DstFpDataVer);
innerCmd.clear();
innerCmd.setBytCmd(sCmdParam);
innerCmd.appendBinData(bytFpData);
log.i(csFuncName, "2 - 6 - ");
return true;
} else if (cmd.getCmdCode().equals("SET_USER_INFO")) {
int k, m;
log.i(csFuncName, "3 - 2 - ");
List<EnrollData> listEnrollData = new ArrayList<EnrollData>();
String user_id;
String user_name;
String user_privilege;
byte[] user_photo = new byte[0];
try {
user_id = jobjCmdParam.getStr("user_id");
user_name = jobjCmdParam.getStr("user_name");
user_privilege = jobjCmdParam.getStr("user_privilege");
if (!jobjCmdParam.isNull("user_photo")) {
log.i(csFuncName, "3 - 3 - ");
String sTemp;
sTemp = jobjCmdParam.getStr("user_photo");
m = Integer.parseInt(sTemp.substring(4, sTemp.length()));
if (m >= 1)
user_photo = GetBinDataFromBSCommBinData(m, cmd.getBytCmd());
}
log.i(csFuncName, "3 - 4 - ");
EnrollData ed;
JSONObject jobjOneED;
if (jobjCmdParam.containsKey("enroll_data_array") && !jobjCmdParam.isNull("enroll_data_array")) {
JSONArray jarrEnrollData = jobjCmdParam.getJSONArray("enroll_data_array");
for (k = 0; k < jarrEnrollData.size(); k++) {
String sTemp;
byte[] bytTemp;
jobjOneED = jarrEnrollData.getJSONObject(k);
ed = new EnrollData();
ed.setBackupNumber(Integer.parseInt(jobjOneED.getStr("backup_number")));
log.i(csFuncName, "3 - 5 - k=" + k);
sTemp = jobjOneED.getStr("enroll_data");
if (sTemp.length() < 5) {
log.e(csFuncName, "3 - 5.1 - k=" + k);
return false;
}
log.i(csFuncName, "3 - 6 - k=" + k);
m = Integer.parseInt(sTemp.substring(4));
if (m < 1) {
log.e(csFuncName, "3 - 6.1 - k=" + k);
return false;
}
log.i(csFuncName, "3 - 7 - k=" + k + " m=" + m);
bytTemp = GetBinDataFromBSCommBinData(m, cmd.getBytCmd());
ed.setBytData(bytTemp);
listEnrollData.add(ed);
}
}
} catch (Exception ex) {
log.e(csFuncName, "3 - except - " + ex.toString());
return false;
}
log.i(csFuncName, "3 - 11 - ");
if (listEnrollData.size() == 0) {
log.i(csFuncName, "3 - 11 - 1");
return true;
}
log.i(csFuncName, "3 - 12 - ");
JSONObject jobjCmdParamNew = new JSONObject();
jobjCmdParamNew.put("user_id", user_id);
jobjCmdParamNew.put("user_name", user_name);
jobjCmdParamNew.put("user_privilege", user_privilege);
log.i(csFuncName, "3 - 13 - ");
JSONArray jarrED = new JSONArray();
EnrollData ed1 = null;
m = 1;
for (k = 0; k < listEnrollData.size(); k++) {
JSONObject jobjOneED = new JSONObject();
ed1 = listEnrollData.get(k);
jobjOneED.put("backup_number", ed1.getBackupNumber());
String sTemp = "BIN_" + m;
jobjOneED.put("enroll_data", sTemp);
jarrED.put(jobjOneED);
m++;
}
jobjCmdParamNew.put("enroll_data_array", jarrED);
log.i(csFuncName, "3 - 14 - ");
if (user_photo.length > 0)
jobjCmdParamNew.put("user_photo", "BIN_" + m);
log.i(csFuncName, "3 - 15 - ");
sCmdParam = jobjCmdParamNew.toString();
innerCmd.setBytCmd(sCmdParam);
for (k = 0; k < listEnrollData.size(); k++) {
ed1 = listEnrollData.get(k);
log.i(csFuncName, "3 - 15.2 - size = " + ed1.getBytData().length);
cmd.appendBinData(ed1.getBytData());
}
log.i(csFuncName, "3 - 16 - ");
if (user_photo.length > 0)
cmd.appendBinData(user_photo);
log.i(csFuncName, "3 - 17 - ");
return true;
} else {
log.i(csFuncName, "3 - 18 - ");
return true;
}
} catch (Exception e) {
log.e(csFuncName, "Except - 2 - " + e.toString());
return false;
}
}
// @PostMapping(value = "/")
public void abc() throws UnsupportedEncodingException {
Logoutput("--------------------1--------------------");
String sRequestCode = "";
String sTransId = "";
byte[] bytEmpty = new byte[0];
final String csFuncName = "Page_Load";
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
// 是否打印
log = LogUtil.getInstance(true);
try {
sRequestCode = request.getHeader("request_code");
Logoutput("======================================================================sRequestCode=>"
+ sRequestCode);
if (!MyUtil.isValidEngDigitString(sRequestCode)) {
log.e(csFuncName, "Invalid request_code : " + sRequestCode);
return;
}
sTransId = request.getHeader("trans_id");
if (sTransId == null)
sTransId = "";
log.i(csFuncName, "1 - request_code : " + sRequestCode + " ,trans_id : " + sTransId);
String sDevId = request.getHeader("dev_id");
if (!MyUtil.isValidEngDigitString(sDevId)) {
log.e(csFuncName, "error - Invalid dev_id : " + sDevId);
return;
}
int lenContent = GetRequestStreamBytes(request);
if (lenContent < 0) {
log.e(csFuncName, "2.1" + lenContent);
return;
}
// 块序号
int nBlkNo = 0;
if (request.getHeader("blk_no") != null)
nBlkNo = Integer.parseInt(request.getHeader("blk_no"));
int vRet;
if (nBlkNo > 0) {
vRet = AddBlockData(sDevId, nBlkNo, bytRequestBin);
if (vRet != 0) {
log.e(csFuncName, "3.0 - error - AddBlockData:" + vRet);
SendResponseToClient("ERROR_ADD_BLOCK_DATA", sTransId, "", bytEmpty, response);
return;
}
log.i(csFuncName, "3.1");
SendResponseToClient("OK", sTransId, "", bytEmpty, response);
return;
} else if (nBlkNo < 0) {
SendResponseToClient("ERROR_INVLAID_BLOCK_NO", sTransId, "", bytEmpty, response);
return;
} else {
GetBlockDataAndRemove(sDevId);
bytRequestTotal = ConcateByteArray(bytRequestTotal, bytRequestBin);
}
switch (sRequestCode) {
case Constant.REQ_CODE_RECV_CMD:
RemoveOldBlockStream();
OnReceiveCmd(sDevId, sTransId, bytRequestTotal, response);
break;
case Constant.REQ_CODE_SEND_CMD_RESULT:
OnSendCmdResult(sDevId, sTransId, bytRequestTotal, response, request);
break;
case Constant.REQ_CODE_REALTIME_GLOG:
OnRealtimeGLog(sDevId, bytRequestTotal, response, request);
break;
case Constant.REQ_CODE_REALTIME_ENROLL:
OnRealtimeEnrollData(sDevId, bytRequestTotal, response, request);
break;
case "":
break;
default:
SendResponseToClient("ERROR_INVLAID_REQUEST_CODE", sTransId, "", bytEmpty, response);
break;
}
} catch (Exception e) {
log.e("Page_Load---->" + e.getMessage());
e.printStackTrace();
} finally {
}
}
// 实时登记数据
private void OnRealtimeEnrollData(String asDevId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------2--------------------");
final String csFuncName = "Page_Load - realtime_enroll_data";
String sRequest;
String sResponse;
byte[] bytRequest = abytRequest;
System.err.println("aby:"+abytRequest.toString());
try {
log.i(csFuncName, "1");
sRequest = GetStringFromBSCommBuffer(bytRequest);
System.err.println("sq:"+sRequest);
if (sRequest.length() == 0) {
return;
}
log.i(csFuncName, "2");
JSONObject jobjRequest = new JSONObject(sRequest);
String sUserId = jobjRequest.getStr("user_id");
log.i(csFuncName, "3");
BufferedOutputStream bos = null;
FileOutputStream fos = null;
FileWriter fw = null;
try {
// fw=new FileWriter("E:\\ylwork\\ab3.txt");
// fw.write(new String(bytRequest));
fos = new FileOutputStream(new File(defPath + sUserId));
bos = new BufferedOutputStream(fos);
bos.write(bytRequest);
// JSONObject vResultJson = new JSONObject();
// vResultJson.put("asDevId", asDevId);
// vResultJson.put("asUserId", sUserId);
// vResultJson.put("abytUserData",bytRequest);
// String sFinal = vResultJson.toString();
// String url = serverUrl+"/kqz/sauserregdata";
// HttpHeaders headers = new HttpHeaders();
// MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
// params.add("json", sFinal);
// RestTemplate restTemplate = new RestTemplate();
// HttpEntity httpEntity = new HttpEntity(params, headers);
// restTemplate.postForEntity(url, httpEntity, String.class);
sResponse = "OK";
} catch (Exception ex) {
sResponse = "ERROR_DB_ACCESS";
} finally {
if (bos != null)
bos.close();
if (fos != null)
fos.close();
if (fw != null)
fw.close();
}
response.addHeader("response_code", sResponse);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
log.i(csFuncName, "4");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return;
}
}
// 实时打卡数据
private void OnRealtimeGLog(String asDevId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------3--------------------");
final String csFuncName = "Page_Load - realtime_glog";
String sRequest = "";
String sResponse;
byte[] bytRequest = abytRequest;
byte[] bytLogImage = new byte[0];
try {
log.i(csFuncName, "1------------------>");
Command cmd = new Command();
GetStringAnd1stBinaryFromBSCommBuffer(bytRequest, cmd);
sRequest = cmd.getJsonstr();
bytLogImage = cmd.getBytCmd();
System.err.println("sQequest:"+sRequest);
if (sRequest.length() == 0) {
log.e(csFuncName, "1-- length=" + sRequest.length());
return;
}
log.i(csFuncName, "2");
String sUserId;
String sVerifyMode;
String sIOMode;
String sIOTime;
// String sLogImg;
String sFKBinDataLib;
JSONObject jobjRequest = new JSONObject(sRequest);
log.i(csFuncName, "2-1");
try {
sFKBinDataLib = jobjRequest.getStr("fk_bin_data_lib");
} catch (Exception e) {
log.e(csFuncName, "2-- sFKBinDataLib.length=0");
response.addHeader("response_code", "ERROR_INVALID_LIB_NAME");
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
return;
}
log.i(csFuncName, "2-2");
sUserId = jobjRequest.getStr("user_id");
sVerifyMode = jobjRequest.getStr("verify_mode");
sIOMode = jobjRequest.getStr("io_mode");
sIOTime = jobjRequest.getStr("io_time");
log.i(csFuncName, "2-3");
log.i(csFuncName, "2" + "user_id = " + sUserId + " sIOTime = " + sIOTime);
if (sFKBinDataLib == "FKDataHS101") {
sIOMode = FKDataHS101_GLog.GetInOutModeString(Integer.parseInt(sIOMode));
sVerifyMode = FKDataHS101_GLog.GetVerifyModeString(Integer.parseInt(sVerifyMode));
}
else if (sFKBinDataLib == "FKDataHS100") {
sIOMode = FKDataHS100_GLog.GetInOutModeString(Integer.parseInt(sIOMode));
sVerifyMode = FKDataHS100_GLog.GetVerifyModeString(Integer.parseInt(sVerifyMode));
}
log.i(csFuncName, "3");
sResponse = InsertRealtimeGLog(log, asDevId, sUserId, sVerifyMode, sIOMode, sIOTime, bytLogImage);
response.addHeader("response_code", sResponse);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
log.i(csFuncName, "4");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return;
}
}
// 实时打卡数据保存
public String InsertRealtimeGLog(LogUtil log, String asDevId, String asUserId, String asVerifyMode, String asIOMode,
String asIOTime, byte[] abytLogImage) {
final String csFuncName = "InsertRealtimeGLog";
String sStdIoTime = MyUtil.ConvertFKTimeToNormalTimeString(asIOTime);
log.i(csFuncName, "1 - " + sStdIoTime);
try {
log.i(csFuncName, "2");
if (!MyUtil.isValidEngDigitString(asUserId))
return "ERROR_INVALID_USER_ID";
if (MyUtil.IsNullOrEmptyString(asVerifyMode))
return "ERROR_INVALID_VERIFY_MODE";
if (MyUtil.IsNullOrEmptyString(asIOMode))
return "ERROR_INVALID_IO_MODE";
if (!MyUtil.IsValidTimeString(sStdIoTime))
return "ERROR_INVALID_IO_TIME";
} catch (Exception e) {
log.e(csFuncName, "2 - error");
return "ERROR_INVALID_LOG";
}
try {
log.i(csFuncName, "3");
log.i(csFuncName, "4");
// String strSql;
// strSql = "INSERT INTO kqjg_realtime_glog";
// strSql = strSql + "(update_time, device_id, user_id, verify_mode, io_mode,
// io_time)VALUES('";
// strSql = strSql + TimeToString(new Date()) + "',?,?,?,?,?)";
// String[] params = new
// String[]{asDevId,asUserId,asVerifyMode,asIOMode,sStdIoTime};
// DBUtil.update(strSql, params);
/***********************************************************
* 考勤机打卡---开始
********************************************************************************************/
// KqjgRealtimeGlog glog = KqjgRealtimeGlog.builder().build();
// glog.setUpdateTime(TimeToString(new Date()));
// glog.setDeviceId(asDevId);
// glog.setUserId(asUserId);//打卡用户id
// glog.setVerifyMode(asVerifyMode);//打卡方式 1:指纹 20:人脸
// glog.setIoMode(asIOMode);
// glog.setIoTime(sStdIoTime);//打卡时间
// glog.insertOrUpdate();
// TODO
System.err.println("asDevId:"+asDevId);
System.err.println("asUserId:"+asUserId);
System.err.println("asVerifyMode:"+asVerifyMode);
System.err.println("asIOMode:"+asIOMode);
System.err.println("asIOTime:"+asIOTime);
/*********************************************************************
* 考勤机打卡---结束
********************************************************************************************/
// final String uri = serverUrl+"/kqz/punchclock/" + asDevId + "/" + asUserId + "/" + asVerifyMode
// + "/0/" + sStdIoTime;
// RestTemplate restTemplate = new RestTemplate();
// String result = restTemplate.getForObject(uri, String.class);
JSONObject vResultJson = new JSONObject();
vResultJson.put("asDevId", asDevId);
vResultJson.put("asUserId", asUserId);
vResultJson.put("asVerifyMode", asVerifyMode);
vResultJson.put("sStdIoTime", sStdIoTime);
String sFinal = vResultJson.toString();
// String url = serverUrl + "/kqz/punchclock";
// HttpHeaders headers = new HttpHeaders();
// MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
// params.add("json", sFinal);
// RestTemplate restTemplate = new RestTemplate();
// HttpEntity httpEntity = new HttpEntity(params, headers);
// ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);
log.i(csFuncName, "5");
if (SaveLogImageToFile(log, asDevId, asUserId, asIOTime, abytLogImage) != 0) {
log.e(csFuncName, "Error to save log image");
return "ERROR_SAVE_LOG_IMAGE";
}
log.i(csFuncName, "6");
return "OK";
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return "ERROR_DB_ACCESS";
}
}
// 保存图片
private int SaveLogImageToFile(LogUtil log, String asDevId, String asUserId, String asIOTime, byte[] abytLogImage) {
final String csFuncName = "SaveLogImageToFile";
String sLogImgFolder;
try {
log.i(csFuncName, "0");
if (abytLogImage.length < 1)
return 0;
log.i(csFuncName, "2");
// config
File f = new File(defimgPath);
sLogImgFolder = f.getParentFile().getAbsolutePath() + File.separator + asIOTime.substring(0, 8);
f = new File(sLogImgFolder);
if (!f.exists())
f.mkdir();
log.i(csFuncName, "3 - " + sLogImgFolder);
FileOutputStream fs = new FileOutputStream(
sLogImgFolder + File.separator + asUserId + "_" + asIOTime + ".jpg");
fs.write(abytLogImage, 0, abytLogImage.length);
fs.flush();
fs.close();
log.i(csFuncName, "4");
return 0;
} catch (Exception ex) {
log.e(csFuncName, "Except - " + ex.getMessage());
return -100;
}
}
private void OnSendCmdResult(String asDevId, String sTransId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------4--------------------");
final String csFuncName = "Page_Load - send_cmd_result";
byte[] bytCmdResult = abytRequest;
String sReturnCode;
log.i(csFuncName, "1");
try {
log.i(csFuncName, "2 - trans_id:" + sTransId);
Command cmd = new Command();
// 重启
// if (CheckResetCmd(log, asDevId, cmd)) {
// log.i(csFuncName, "2.1");
// SendResponseToClient("RESET_FK", sTransId, "", bytEmpty, response);
// return;
// }
// 取消命令
// if (IsCancelledCmd(log, asDevId, sTransId)) {
// log.i(csFuncName, "2.2");
// SendResponseToClient("ERROR_CANCELED", sTransId, "", bytEmpty, response);
// return;
// }
log.i(csFuncName, "3");
sReturnCode = request.getHeader("cmd_return_code").toString();
SetCmdResult(log, sTransId, asDevId, sReturnCode, bytCmdResult, cmd);
log.i(csFuncName, "4");
SendResponseToClient(cmd.getsResponse(), cmd.getTransId(), cmd.getCmdCode(), cmd.getBytCmd(), response);
log.i(csFuncName, "5");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.toString());
return;
}
}
private void OnReceiveCmd(String asDevId, String asTransId, byte[] abytRequest, HttpServletResponse response) {
Logoutput("--------------------5--------------------");
final String csFuncName = "Page_Load - receive_cmd";
String sRequest;
byte[] bytRequest = abytRequest;
try {
log.i(csFuncName, "2");
sRequest = GetStringFromBSCommBuffer(bytRequest);
if (sRequest.length() == 0) {
return;
}
Device dev = Device.addDevice(asDevId, sRequest);
log.i(csFuncName, "3 - DevName=" + dev.getFk_name() + ", DevTime=" + dev.getFk_time() + ", DevInfo="
+ dev.getFk_info());
// 检查命令
// Command cmd = new Command(sTransId, sCmdCode, new byte[0], sResponse);
// ReceiveCmd(log, dev, cmd);
Command cmd = dev.getCmd();
log.i(csFuncName, "4");
SendResponseToClient(cmd.getsResponse(), cmd.getTransId(), cmd.getCmdCode(), cmd.getBytCmd(), response);
log.i(csFuncName, "5");
} catch (Exception ex) {
log.i(csFuncName, "Except - 1 - " + ex.toString());
// ex.printStackTrace();
return;
}
}
private int GetRequestStreamBytes(HttpServletRequest request) {
Logoutput("--------------------6--------------------");
int lenContent = request.getContentLength();
if (lenContent < 1)
return 0;
InputStream streamIn;
byte[] bytRecv = new byte[lenContent];
try {
streamIn = request.getInputStream();
int lenRead = 0, readlen = 0;
while ((readlen = streamIn.read(bytRecv, lenRead, 1024)) != -1) {
lenRead += readlen;
}
// lenRead = streamIn.read(bytRecv, 0, lenContent);
if (lenRead != lenContent) {
return -1;
}
} catch (IOException e) {
e.printStackTrace();
}
bytRequestBin = bytRecv;
return lenContent;
}
private void RemoveOldBlockStream() {
Logoutput("--------------------7--------------------");
Date dtCur = new Date();
try {
List<String> listDevIdKey = new ArrayList<String>();
FKWebTransBlockData app_val_blk;
Iterator<Entry<String, FKWebTransBlockData>> iter = Constant.Application.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, FKWebTransBlockData> entry = (Map.Entry<String, FKWebTransBlockData>) iter.next();
String sKey = entry.getKey();
if (!sKey.equalsIgnoreCase("key_dev_"))
continue;
app_val_blk = entry.getValue();
if (dtCur.getTime() - app_val_blk.TmLastModified.getTime() > 1000 * 60 * 30) {
listDevIdKey.add(sKey);
}
}
for (int i = 0; i < listDevIdKey.size(); i++) {
Constant.Application.remove(listDevIdKey.get(i));
}
} catch (Exception e) {
log.e(e.getMessage());
}
}
private int GetBlockDataAndRemove(String asDevId) {
Logoutput("--------------------8--------------------");
bytRequestTotal = new byte[0];
if (asDevId.length() == 0)
return -1;
try {
String app_key;
app_key = "key_dev_" + asDevId;
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
log.i("GetBlockDataAndRemove->", "app_val_blk == null");
return 0;
}
bytRequestTotal = Arrays.copyOf(app_val_blk.getAbytBlkData(), app_val_blk.getAbytBlkData().length);
Constant.Application.remove(app_key);
return 0;
} catch (Exception e) {
return -11;
}
}
private int AddBlockData(String asDevId, int anBlkNo, byte[] abytBlkData) {
Logoutput("--------------------9--------------------");
if (asDevId.length() == 0)
return -1; // -1 :
if (anBlkNo < 1)
return -1;
if (abytBlkData.length == 0)
return -1;
try {
String app_key;
app_key = "key_dev_" + asDevId;
if (anBlkNo == 1) {
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
app_val_blk = new FKWebTransBlockData();
Constant.Application.put(app_key, app_val_blk);
} else {
Constant.Application.remove(app_key);
app_val_blk = new FKWebTransBlockData();
Constant.Application.put(app_key, app_val_blk);
}
app_val_blk.LastBlockNo = 1;
app_val_blk.setAbytBlkData(abytBlkData);
} else {
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
return -2;
}
if (app_val_blk.LastBlockNo != anBlkNo - 1) {
return -3;
}
app_val_blk.LastBlockNo = anBlkNo;
app_val_blk.setAbytBlkData(abytBlkData);
}
return 0;
} catch (Exception e) {
return -11;
}
}
private void SendResponseToClient(String asResponseCode, String asTransId, String asCmdCode, byte[] abytCmdParam,
HttpServletResponse response) {
Logoutput("--------------------10--------------------");
response.addHeader("response_code", asResponseCode);
response.addHeader("trans_id", asTransId);
response.addHeader("cmd_code", asCmdCode);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", String.valueOf(abytCmdParam.length));
try {
if (abytCmdParam.length > 0) {
OutputStream streamOut = response.getOutputStream();
streamOut.write(abytCmdParam, 0, abytCmdParam.length);
streamOut.close();
}
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
public String GetStringFromBSCommBuffer(byte[] abytBSComm) {
if (abytBSComm.length < 4)
return "";
try {
String sRet;
int lenText = MyUtil.byte2int(abytBSComm);
if (lenText > abytBSComm.length - 4)
return "";
if (lenText == 0)
return "";
if (abytBSComm[4 + lenText - 1] == 0) // if last value of string buufer is 0x0
sRet = MyUtil.byte2String(abytBSComm, 4, lenText - 1);
else
sRet = MyUtil.byte2String(abytBSComm, 4, lenText);
return sRet;
} catch (Exception e) {
return "";
}
}
public byte[] ConcateByteArray(byte[] abytDest, byte[] abytSrc) {
int len_dest = abytDest.length + abytSrc.length;
if (abytSrc.length == 0)
return abytDest;
byte[] bytTmp = new byte[len_dest];
System.arraycopy(abytDest, 0, bytTmp, 0, abytDest.length);
System.arraycopy(abytSrc, 0, bytTmp, abytDest.length, abytSrc.length);
return bytTmp;
}
// 更新固件
private boolean MakeUpdateFirmwareCmdParamBin(LogUtil log, String devId, String asDevInfo, Command cmd) {
final String csFuncName = "MakeUpdateFirmwareCmdParamBin";
if (!cmd.getCmdCode().equals("UPDATE_FIRMWARE"))
return true;
log.i(csFuncName, "1 - ");
FileInputStream fs = null;
try {
JSONObject jobjDevInfo = new JSONObject(asDevInfo);
final String sPrefix = jobjDevInfo.getStr("firmware_filename");
log.i(csFuncName, "2 - prefix:" + sPrefix);
// config
File f = new File("G:/Temp/BSFirmware/");
log.i(csFuncName, "3 - firmware file Dir:" + f.getAbsolutePath());
File[] FirmwareFiles = f.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.startsWith(sPrefix) && name.endsWith(".bin"))
return true;
return false;
}
});
if (FirmwareFiles == null || FirmwareFiles.length == 0) {
// String sSql = "UPDATE kqjg_fkcmd_trans SET
// return_code='ERROR_NO_FIRMWARE_FILE', status='CANCELLED', update_time = NOW()
// WHERE trans_id='" + cmd.getTransId() + "'";
// DBUtil.update(sSql, null);
// KqjgFkcmdTrans trans =
// KqjgFkcmdTrans.builder().returnCode("ERROR_NO_FIRMWARE_FILE").status("CANCELLED").updateTime(TimeToString(new
// Date())).build();
// UpdateWrapper<KqjgFkcmdTrans> userUpdateWrapper = new UpdateWrapper<>();
// userUpdateWrapper.eq("trans_id", cmd.getTransId());
// trans.update(userUpdateWrapper);
return false;
}
log.i(csFuncName, "4 - firmware file:" + FirmwareFiles[0].getName());
byte[] bytFirmwareBin = new byte[(int) FirmwareFiles[0].length()];
fs = new FileInputStream(FirmwareFiles[0]);
int offset = 0;
int numRead = 0;
while (numRead >= 0) {
if (offset < bytFirmwareBin.length)
break;
numRead = fs.read(bytFirmwareBin, offset, bytFirmwareBin.length - offset);
offset += numRead;
}
log.i(csFuncName, "5 - ");
String sFileTitle = FirmwareFiles[0].getName();
String sCmdParam = "{\"firmware_file_name\":\"" + sFileTitle + "\",\"firmware_bin_data\":\"BIN_1\"}";
cmd.setBytCmd(sCmdParam);
cmd.appendBinData(bytFirmwareBin);
return true;
} catch (Exception e) {
log.e(csFuncName, "Exception : " + e.getMessage());
return false;
} finally {
if (fs != null)
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] GetBinDataFromBSCommBinData(int anOrder, byte[] bytBSComm) {
byte[] bytEmpty = new byte[0];
try {
// Convert SQLSever Data types to C# data types
// SQLSever Data type (varbinary) <-> C# data type (byte [])
Logoutput("bytBSComm = " + bytBSComm.length);
if (bytBSComm.length < 4)
return bytEmpty;
if (anOrder < 0 || anOrder > 255)
return bytEmpty;
int orderBin;
int posBin;
int lenBin;
int lenText = MyUtil.byte2int(bytBSComm);
Logoutput("lenText = " + lenText);
if (lenText > bytBSComm.length - 4)
return bytEmpty;
posBin = 4 + lenText;
orderBin = 0;
while (true) {
Logoutput("posBin = " + posBin);
if (posBin > bytBSComm.length - 4)
return bytEmpty;
lenBin = MyUtil.byte2int(bytBSComm, posBin);
Logoutput("lenBin = " + lenBin);
Logoutput("comparelen = " + (bytBSComm.length - posBin - 4));
if (lenBin > bytBSComm.length - posBin - 4)
return bytEmpty;
orderBin++;
if (orderBin == anOrder)
break;
posBin = posBin + 4 + lenBin;
}
byte[] bytRet = new byte[lenBin];
System.arraycopy(bytBSComm, posBin + 4, bytRet, 0, lenBin);
Logoutput("bytRet = " + bytRet.length);
return bytRet;
} catch (Exception e) {
Logoutput("err");
return bytEmpty;
}
}
public void SetCmdResult(LogUtil log, String asTransId, String asDevId, String asReturnCode, byte[] abytCmdResult,
Command cmd) {
final String csFuncName = "SetCmdResult";
log.i(csFuncName, "0 - trans_id:" + asTransId + ", dev_id:" + asDevId);
log.i(csFuncName, "1");
try {
// Thread.sleep(10000);
log.i(csFuncName, "2");
if (SaveCmdResultLogData(log, asTransId, asDevId, abytCmdResult) == false) {
cmd.setsResponse("ERROR_DB_SAVE_LOG");
return;
}
if (SaveUserIdList(log, asTransId, asDevId, abytCmdResult) == false) {
cmd.setsResponse("ERROR_DB_SAVE_USER_ID_LIST");
return;
}
// pstmt = sqlConn.prepareStatement("{call dbo.usp_set_cmd_result(?,?,?,?)}");
// pstmt = sqlConn.prepareStatement("call usp_set_cmd_result(?,?,?,?)");
// pstmt.setString(1, asDevId);
// pstmt.setString(2, asTransId);
// pstmt.setString(3, asReturnCode);
// pstmt.setBytes(4, abytCmdResult);
// pstmt.execute();
// kqjgfkcmdtransmapper.call(asDevId,asTransId,asReturnCode,abytCmdResult);
log.i(csFuncName, "3");
cmd.setsResponse("OK");
return;
} catch (Exception e) {
log.e(csFuncName, "Except - 1 - " + e.toString());
cmd.setsResponse("ERROR_DB_ACCESS");
return;
}
}
// 保存user id list
private boolean SaveUserIdList(LogUtil log, String asTransId, String asDevId, byte[] abytCmdResult) {
final String csFuncName = "SaveUserIdList";
log.i(csFuncName, "1");
log.i(csFuncName, "2" + " astrans_id = " + asTransId);
log.i(csFuncName, "3");
String sFKDataLib = "";
String sJson;
byte[] bytUserIdList;
Command cmd = new Command();
Logoutput("sFKDataLib->" + sFKDataLib);
GetStringAnd1stBinaryFromBSCommBuffer(abytCmdResult, cmd);
sJson = cmd.getJsonstr();
bytUserIdList = cmd.getBytCmd();
if (sJson.length() == 0)
return false;
Logoutput("sJson->" + sJson);
log.i(csFuncName, "4");
int cntUserId, sizeOneUserId;
try {
JSONObject jobjLogInfo = new JSONObject(sJson);
cntUserId = jobjLogInfo.getInt("user_id_count");
sizeOneUserId = jobjLogInfo.getInt("one_user_id_size");
if (bytUserIdList.length < cntUserId * sizeOneUserId)
return false;
log.i(csFuncName, "5");
if (!"FKDataHS101".equalsIgnoreCase(sFKDataLib) && !"FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
log.e(csFuncName, "error - 1");
return false;
}
if (sizeOneUserId != 8)
return false;
log.i(csFuncName, "6 - HS101");
// String sSqlTemp = "DELETE FROM " + csTblUserId + " WHERE trans_id='" +
// asTransId +
// "' AND device_id='" + asDevId + "'";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList.builder().build().delete(
// new
// QueryWrapper<KqjgFkcmdTransCmdResultUserIdList>().lambda().eq(KqjgFkcmdTransCmdResultUserIdList::getTransId,
// asTransId)
// .eq(KqjgFkcmdTransCmdResultUserIdList::getDeviceId, asDevId));
int k;
byte[] bytOneUserId = new byte[sizeOneUserId];
byte[] bytEnrolledFlag;
for (k = 0; k < cntUserId; k++) {
int nEnrollDataCount = 0;
System.arraycopy(bytUserIdList, k * sizeOneUserId, bytOneUserId, 0, sizeOneUserId);
if ("FKDataHS101".equalsIgnoreCase(sFKDataLib)) {
FKDataHS101_UserIdInfo usrid = new FKDataHS101_UserIdInfo(bytOneUserId);
String sUserId = String.valueOf(usrid.UserId);
bytEnrolledFlag = usrid.GetBackupNumberEnrolledFlag();
for (int bkn = 0; bkn < bytEnrolledFlag.length; bkn++) {
if (bytEnrolledFlag[bkn] == 1) {
nEnrollDataCount++;
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += bkn + ")";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(bkn);
// glog.insertOrUpdate();
}
}
if (nEnrollDataCount == 0) {
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += "-1)";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(-1);
// glog.insertOrUpdate();
}
} else if ("FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
FKDataHS100_UserIdInfo usrid = new FKDataHS100_UserIdInfo(bytOneUserId);
String sUserId = String.valueOf(usrid.UserId);
int BackupNumber = (int) usrid.BackupNumber;
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += BackupNumber + ")";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(BackupNumber);
// glog.insertOrUpdate();
}
}
log.i(csFuncName, "7 - HS101");
} catch (Exception ex) {
log.e(csFuncName, "error - 2 - " + ex.toString());
return false;
}
log.i(csFuncName, "8");
return true;
}
// 保存命令结果
private boolean SaveCmdResultLogData(LogUtil log, String asTransId, String asDevId, byte[] abytCmdResult) {
final String csFuncName = "SaveCmdResultLogData";
log.i(csFuncName, "3");
String sFKDataLib = "";
String sJson;
byte[] bytLogList;
Command cmd = new Command();
GetStringAnd1stBinaryFromBSCommBuffer(abytCmdResult, cmd);
sJson = cmd.getJsonstr();
bytLogList = cmd.getBytCmd();
if (sJson.length() == 0)
return false;
log.i(csFuncName, "4");
int cntLog, sizeOneLog;
try {
JSONObject jobjLogInfo = new JSONObject(sJson);
cntLog = jobjLogInfo.getInt("log_count");
sizeOneLog = jobjLogInfo.getInt("one_log_size");
if (bytLogList.length < cntLog * sizeOneLog)
return false;
log.i(csFuncName, "5 log count=" + cntLog);
if (!"FKDataHS101".equalsIgnoreCase(sFKDataLib) && !"FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
log.e(csFuncName, "error - 1");
return false;
}
if (sizeOneLog != 12)
return false;
log.i(csFuncName, "6 - HS101");
// String sSqlTemp = "DELETE FROM " + csTblLog + " WHERE trans_id='" + asTransId
// +
// "' AND device_id='" + asDevId + "'";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultLogData.builder().build().delete(
// new
// QueryWrapper<KqjgFkcmdTransCmdResultLogData>().lambda().eq(KqjgFkcmdTransCmdResultLogData::getTransId,
// asTransId)
// .eq(KqjgFkcmdTransCmdResultLogData::getDeviceId, asDevId));
int k;
byte[] bytOneLog = new byte[sizeOneLog];
for (k = 0; k < cntLog; k++) {
System.arraycopy(bytLogList, k * sizeOneLog, bytOneLog, 0, sizeOneLog);
log.i("debug:", "6 - HS101 bytOneLog=" + Arrays.toString(bytOneLog));
if ("FKDataHS101".equalsIgnoreCase(sFKDataLib)) {
FKDataHS101_GLog glog = new FKDataHS101_GLog(bytOneLog);
String sUserId = String.valueOf(glog.UserId);
String sIoMode = FKDataHS101_GLog.GetInOutModeString(glog.IoMode);
String sVerifyMode = FKDataHS101_GLog.GetVerifyModeString(glog.VerifyMode);
String sIoTime = glog.GetIoTimeString();
// sSqlTemp = "INSERT INTO " + csTblLog;
// sSqlTemp += "(trans_id, device_id, user_id, verify_mode, io_mode, io_time)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', '";
// sSqlTemp += sVerifyMode + "', '";
// sSqlTemp += sIoMode + "', '";
// sSqlTemp += sIoTime + "')";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultLogData logdata =
// KqjgFkcmdTransCmdResultLogData.builder().build();
// logdata.setTransId(Integer.valueOf(asTransId));
// logdata.setDeviceId(asDevId);
// logdata.setUserId(sUserId);
// logdata.setVerifyMode(sVerifyMode);
// logdata.setIoMode(sIoMode);
// logdata.setIoTime(sIoTime);
// logdata.insertOrUpdate();
} else if ("FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
FKDataHS100_GLog glog = new FKDataHS100_GLog(bytOneLog);
String sUserId = String.valueOf(glog.UserId);
String sIoMode = FKDataHS100_GLog.GetInOutModeString(glog.IoMode);
String sVerifyMode = FKDataHS100_GLog.GetVerifyModeString(glog.VerifyMode);
String sIoTime = glog.GetIoTimeString();
// sSqlTemp = "INSERT INTO " + csTblLog;
// sSqlTemp += "(trans_id, device_id, user_id, verify_mode, io_mode, io_time)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', '";
// sSqlTemp += sVerifyMode + "', '";
// sSqlTemp += sIoMode + "', '";
// sSqlTemp += sIoTime + "')";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultLogData logdata =
// KqjgFkcmdTransCmdResultLogData.builder().build();
// logdata.setTransId(Integer.valueOf(asTransId));
// logdata.setDeviceId(asDevId);
// logdata.setUserId(sUserId);
// logdata.setVerifyMode(sVerifyMode);
// logdata.setIoMode(sIoMode);
// logdata.setIoTime(sIoTime);
// logdata.insertOrUpdate();
}
}
log.i(csFuncName, "7 - HS101");
} catch (Exception ex) {
log.e(csFuncName, "error - 2 - " + ex.toString());
return false;
}
log.i(csFuncName, "8");
return true;
}
public void GetStringAnd1stBinaryFromBSCommBuffer(byte[] abytBSComm, Command cmd) {
if (abytBSComm.length < 4)
return;
try {
int lenText = MyUtil.byte2int(abytBSComm);
if (lenText > abytBSComm.length - 4)
return;
if (lenText == 0) {
cmd.setJsonstr("");
} else {
if (abytBSComm[4 + lenText - 1] == 0) // if last value of string buufer is 0x0
cmd.setJsonstr(MyUtil.byte2String(abytBSComm, 4, lenText - 1));
else
cmd.setJsonstr(MyUtil.byte2String(abytBSComm, 4, lenText));
}
int posBin = 4 + lenText;
int lenBin = MyUtil.byte2int(abytBSComm, posBin);
if (lenBin < 1)
return;
if (lenBin > abytBSComm.length - posBin - 4)
return;
cmd.setBytCmd(new byte[lenBin]);
System.arraycopy(abytBSComm, posBin + 4, cmd.getBytCmd(), 0, lenBin);
return;
} catch (Exception e) {
return;
}
}
@Value("${config.environmental-science}")
public String environmental_science;
public void Logoutput(String science) {
if(!("pro").equals(environmental_science)) {
System.out.println(science);
}else {
System.out.println("");
}
}
}
/**
* <p>Title: SetUsersController.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.ctrl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsResponse;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTask;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTaskRelation;
import com.yl8timer.kqj.yl8timer.tools.HSTools;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
/**
* <p>
* Title: SetUsersController.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
@Component
public class SetUsersController implements SchedulingConfigurer {
@Value("${config.ontime.cron}")
private String cron;
@Value("${config.ontime.overtime}")
private Integer overtime;
@Autowired
private HSTools hsTools;
// 数据库动态更改定时配置
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 任务逻辑
setUsersInfo();
updateStatus();
}, triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(cron); // cron配置
return cronTrigger.nextExecutionTime(triggerContext); // 下次执行任务的时间
});
}
/**
* 同步到新设备
*/
@Transactional
private void setUsersInfo() {
List<FkTask> list = FkTask.builder().build()
.selectList(new LambdaQueryWrapper<FkTask>().eq(FkTask::getStatus, 1)); // 查询待执行任务
Integer taskID = null;
for (FkTask fkTask : list) { // 遍历待执行任务
taskID = fkTask.getId(); // 任务id
List<FkTaskRelation> fkTaskRelations = FkTaskRelation.builder().build()
.selectList(new LambdaQueryWrapper<FkTaskRelation>().eq(FkTaskRelation::getTaskId, taskID));
String setTransId = null;
for (FkTaskRelation fkTaskRelation : fkTaskRelations) {
setTransId = fkTaskRelation.getSetTransId();
String getTransId = fkTaskRelation.getGetTransId(); // get标识
FkHsRequest fkHsRequest = FkHsRequest.builder().build()
.selectOne(new LambdaQueryWrapper<FkHsRequest>().eq(FkHsRequest::getId, getTransId)); // 通过get标识查询请求状态
FkHsResponse fkHsResponse = FkHsResponse.builder().build()
.selectOne(new LambdaQueryWrapper<FkHsResponse>().eq(FkHsResponse::getTransId, getTransId)); // 通过get标识查询响应状态
if (fkHsRequest.getStatus() != null) {
try {
if (setTransId == null) {
setTransId = hsTools.setUserInfo(fkTask.getNewDevId(), fkHsResponse.getTotalByte()); // 导入数据响应的transId
}
fkTaskRelation.setSetTransId(setTransId);
fkTaskRelation.insertOrUpdate();
} catch (Exception e) {
Logoutput("请确认考勤机连接状态");
e.getStackTrace();
}
}
}
}
}
private void updateStatus() {
List<FkTask> list = FkTask.builder().build()
.selectList(new LambdaQueryWrapper<FkTask>().eq(FkTask::getStatus, 1)); // 查询待执行任务
for (FkTask fkTask : list) {
long minute = DateUtil.between(fkTask.getCreatedTime(), new Date(), DateUnit.MINUTE, true);
if (minute > overtime) {
fkTask.setStatus(3);
fkTask.setSuccessTime(new Date());
fkTask.insertOrUpdate();
}
Integer count = 0;
Integer taskId = fkTask.getId();
List<FkTaskRelation> fkTaskRelations = FkTaskRelation.builder().build()
.selectList(new LambdaQueryWrapper<FkTaskRelation>().eq(FkTaskRelation::getTaskId, taskId));
for (FkTaskRelation fkTaskRelation : fkTaskRelations) {
String setTransId = fkTaskRelation.getSetTransId();
FkHsRequest fkHsRequest = FkHsRequest.builder().build().selectOne(new LambdaQueryWrapper<FkHsRequest>()
.eq(FkHsRequest::getId, setTransId).eq(FkHsRequest::getStatus, "OK"));
if (fkHsRequest != null) {
count++;
}
}
Logoutput(String.valueOf(count));
Logoutput(String.valueOf(fkTaskRelations.size()));
if (count == fkTaskRelations.size()) {
fkTask.setStatus(2);
fkTask.setSuccessTime(new Date());
fkTask.insertOrUpdate();
}
}
}
@Value("${config.environmental-science}")
public String environmental_science;
public void Logoutput(String science) {
if(!("pro").equals(environmental_science)) {
System.out.println(science);
}else {
System.out.println("");
}
}
}
\ No newline at end of file
/**
* <p>Title: TaskController.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.ctrl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkDev;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTaskRelation;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTask;
import com.yl8timer.kqj.yl8timer.tools.HSTools;
import com.yl8timer.kqj.yl8timer.tools.Result;
import com.yl8timer.kqj.yl8timer.tools.ResultUtil;
/**
* <p>
* Title: TaskController.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
@RestController
@RequestMapping(value = "/task", produces = { "application/json" })
public class TaskController {
@Autowired
private HSTools hsTools;
@PostMapping("/addTask")
@Transactional
public Result<Integer> addDev(@RequestParam List<String> userIds, @RequestParam String oldDevId,
@RequestParam String newDevId) {
// 判断机器类型
FkDev fkDev1 = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, oldDevId));
FkDev fkDev2 = FkDev.builder().build().selectOne(new LambdaQueryWrapper<FkDev>().eq(FkDev::getDevId, newDevId));
if (fkDev1 == null || fkDev2 == null)
return ResultUtil.error("请先绑定考勤机");
Integer code1 = fkDev1.getOrgCode();
Integer code2 = fkDev2.getOrgCode();
if (code1 != code2)
return ResultUtil.error("不同品牌考勤机无法同步用户数据");
if ((code1 == 1 && code2 == 1) || (code1 == 2 && code2 == 2)) { // 1-浩顺 2-浩顺3代
FkTask fkTask = new FkTask();
fkTask.setCreatedTime(new Date());
fkTask.setOldDevId(oldDevId);
fkTask.setNewDevId(newDevId);
fkTask.setStatus(0);
fkTask.insert();
Integer taskId = fkTask.getId(); // 任务id
for (String userId : userIds) {
FkTaskRelation fkTaskRelation = new FkTaskRelation();
fkTaskRelation.setTaskId(taskId);
fkTaskRelation.setUserId(userId);
String transId = null;
try {
transId = hsTools.getUserInfo(oldDevId, userId);
} catch (Exception e) {
return ResultUtil.error("请确保考勤机设备已连接服务器");
}
fkTaskRelation.setGetTransId(transId);
fkTaskRelation.insert();
}
fkTask.setStatus(1);
fkTask.insertOrUpdate();
return ResultUtil.data(fkTask.getId(), "任务添加成功,等待设备响应完成");
} else {
return ResultUtil.error("请联系管理员");
}
}
}
/**
* <p>Title: delLogController.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月13日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.ctrl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsResponse;
import com.yl8timer.kqj.yl8timer.tools.Constant;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
/**
* <p>
* Title: delLogController.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月13日
* @version 1.0
*/
@Component
public class delLogController implements SchedulingConfigurer {
@Value("${config.retry.day}")
private Integer day;
@Value("${config.retry.cron2}")
private String cron2;
// 数据库动态更改定时配置
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 任务逻辑
delLog();
}, triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(cron2); // cron配置 30min/次
return cronTrigger.nextExecutionTime(triggerContext); // 下次执行任务的时间
});
}
private void delLog() {
DateTime newDate = DateUtil.offsetDay(new Date(), -day); // 时间偏移
List<FkHsResponse> list = FkHsResponse.builder().build().selectList(new LambdaQueryWrapper<FkHsResponse>()
.eq(FkHsResponse::getCommand, Constant.REQ_CODE_RECV_CMD).lt(FkHsResponse::getTime, newDate));
for (FkHsResponse fkHsResponse : list) {
fkHsResponse.deleteById();
}
List<FkHsRequest> list2 = FkHsRequest.builder().build().selectList(new LambdaQueryWrapper<FkHsRequest>()
.lt(FkHsRequest::getTime, newDate));
for (FkHsRequest fkHsRequest : list2) {
fkHsRequest.deleteById();
}
}
}
package com.yl8timer.kqj.yl8timer.ctrl;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkData;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
* Title: retryUtil.java Description: 重试机制-配置yml固定时间扫描是否有未转发成功的数据 上限10次
*
* @author dsc
* @date 2020年5月12日
* @version 1.0
*/
@Component
public class retryController implements SchedulingConfigurer {
@Value("${config.retry.cron}")
private String cron;
// 数据库动态更改定时配置
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 任务逻辑
retry();
}, triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(cron); // cron配置 30min/次
return cronTrigger.nextExecutionTime(triggerContext); // 下次执行任务的时间
});
}
/**
* 重试转发数据
*/
private void retry() {
List<FkData> fkDataList = FkData.builder().build()
.selectList(new LambdaQueryWrapper<FkData>().eq(FkData::getIsSuccess, 0).lt(FkData::getTimes, 10));
for (FkData fkData : fkDataList) {
// 封装json对象
JSONObject vResultJson = new JSONObject();
vResultJson.put("dev_id", fkData.getDevId());
vResultJson.put("user_id", fkData.getUserId());
vResultJson.put("verify_mode", fkData.getVerifyMode());
vResultJson.put("io_time", fkData.getIoTime());
String sFinal = vResultJson.toString();
JSONObject jsonObject = null;
try {
// 封装http请求
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("json", sFinal);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(
params, headers);
ResponseEntity<String> request = restTemplate.postForEntity(fkData.getUrl(), httpEntity, String.class);
jsonObject = JSONUtil.parseObj(request.getBody()); // 封装为json对象
} catch (Exception e) {
fkData.setResultDetail("请求地址不存在或目标服务器未开启");
e.getStackTrace();
} finally {
if (jsonObject != null) {
fkData.setResultDetail(jsonObject.toString()); // 请求结果json对象字符串
if (jsonObject.getStr("code").equals("200")) {
fkData.setIsSuccess(1);
}
}
Integer times = fkData.getTimes();
times++;
fkData.setTimes(times); // 更新请求次数
fkData.insertOrUpdate();
}
}
}
}
\ No newline at end of file
/**
* <p>Title: FkDataMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkData;
/**
* <p>Title: FkDataMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
@Repository
public interface FkDataMapper extends BaseMapper<FkData> {
}
/**
* <p>Title: FkDevMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkDev;
/**
* <p>
* Title: FkDevMapper.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Repository
public interface FkDevMapper extends BaseMapper<FkDev> {
}
/**
* <p>Title: FkCommandMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
/**
* <p>Title: FkCommandMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Repository
public interface FkHsRequestMapper extends BaseMapper<FkHsRequest>{
}
/**
* <p>Title: FkCommandMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsResponse;
/**
* <p>Title: FkCommandMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Repository
public interface FkHsResponseMapper extends BaseMapper<FkHsResponse>{
}
/**
* <p>Title: FkDevMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTaskRelation;
/**
* <p>
* Title: FkDevMapper.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Repository
public interface FkTaskMapper extends BaseMapper<FkTaskRelation> {
}
/**
* <p>Title: FkDevMapper.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.dao;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yl8timer.kqj.yl8timer.entity.fk.FkTask;
/**
* <p>
* Title: FkDevMapper.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Repository
public interface FkTaskRelationMapper extends BaseMapper<FkTask> {
}
package com.yl8timer.kqj.yl8timer.entity;
import java.io.UnsupportedEncodingException;
public class Command {
private String TransId;
private String CmdCode;
private byte[] bytCmd;
private String sResponse;
private String jsonstr;
/// 命令
public final static String GET_USER_ID_LIST = "GET_USER_ID_LIST";// 获取用户ID列表
public final static String SET_USER_INFO = "SET_USER_INFO";// 设置用户信息
public final static String GET_USER_INFO = "GET_USER_INFO";// 获取用户信息
public final static String DELETE_USER = "DELETE_USER";// 删除用户
public final static String CLEAR_ENROLL_DATA = "CLEAR_ENROLL_DATA";// 清除所有用户数据
public final static String GET_LOG_DATA = "GET_LOG_DATA";// 按时间获取机器上记录
public final static String CLEAR_LOG_DATA = "CLEAR_LOG_DATA";// 清除设备上所有记录
public final static String SET_TIMEZONE = "SET_TIMEZONE";// 设置门禁时间组
public final static String GET_TIMEZONE = "GET_TIMEZONE";// 获取门禁时间组
public final static String SET_USER_PASSTIME = "SET_USER_PASSTIME";// 设置用户时间段
public final static String GET_USER_PASSTIME = "GET_USER_PASSTIME";// 设置用户时间段
public final static String SET_DEVICE_SETTING = "SET_DEVICE_SETTING";// 设置门禁设备参数
public final static String GET_DEVICE_SETTING = "GET_DEVICE_SETTING";// 获取门禁设备参数
public final static String SET_DOOR_STATUS = "SET_DOOR_STATUS";// 远程开关门(保留)
public final static String SET_TIME = "SET_TIME";// 同步设备时间
public final static String SET_FK_NAME = "SET_FK_NAME";// 设置设备名
public final static String GET_DEVICE_STATUS = "GET_DEVICE_STATUS";// 获取设备存储状态信息
public final static String SET_WEB_SERVER_INFO = "SET_WEB_SERVER_INFO";// 设置设备服务器信息
public final static String UPDATE_FIRMWARE = "UPDATE_FIRMWARE";// 升级设备固件
// response_code 回复状态
// 字段表示是否服务器接收实时登记数据而保存成功。
// OK : 成功
// ERROR : 失败
// 如果机器接受ERROR应答就认为传输失败而再次试图传输到传输成功。
public final static String RESET_FK = "RESET_FK";// 重启设备
public final static String GET_ALL_USER_INFO = "GET_ALL_USER_INFO";// 获取所有用户信息
public final static String CLEAN_MANAGER = "CLEAN_MANAGER";// 一键清除设备管理员
public final static String OK = "OK";
public final static String ERROR = "ERROR";
public final static String ERROR_CANCELED = "ERROR_CANCELED";
public final static String ERROR_ADD_BLOCK_DATA = "ERROR_ADD_BLOCK_DATA";
public final static String ERROR_INVLAID_BLOCK_NO = "ERROR_INVLAID_BLOCK_NO";
public final static String ERROR_INVLAID_REQUEST_CODE = "ERROR_INVLAID_REQUEST_CODE";
public Command() {
TransId = "";
CmdCode = "";
setJsonstr("");
sResponse = "null";
bytCmd = new byte[0];
}
public Command(String transId, String cmdCode, byte[] bytCmd, String sResponse) {
TransId = transId;
CmdCode = cmdCode;
this.bytCmd = bytCmd;
this.sResponse = sResponse;
setJsonstr("");
}
public String getTransId() {
return TransId;
}
public void setTransId(String transId) {
TransId = transId;
}
public String getCmdCode() {
return CmdCode;
}
public void setCmdCode(String cmdCode) {
CmdCode = cmdCode;
}
public byte[] getBytCmd() {
return bytCmd;
}
public void setBytCmd(byte[] bytCmd) {
if (bytCmd == null)
this.bytCmd = new byte[0];
else
this.bytCmd = bytCmd;
}
public void getCmdParam(){
}
public void setBytCmd(String sCmdParam){
byte[] bytCmd = new byte[0];
if (sCmdParam.length() != 0) {
try {
byte[] bytText = sCmdParam.getBytes("UTF-8");
byte[] bytTextLen = int2byte(bytText.length + 1);
bytCmd = new byte[4 + bytText.length + 1];
System.arraycopy(bytTextLen, 0, bytCmd, 0, bytTextLen.length);
System.arraycopy(bytText, 0, bytCmd, 4, bytText.length);
bytCmd[4 + bytText.length] = 0;
} catch (UnsupportedEncodingException e) {
}
}
this.bytCmd = bytCmd;
}
public void appendBinData(byte[] abytToAdd) {
try {
byte[] bytToAdd = abytToAdd;
if (bytToAdd.length == 0)
return;
int len_dest = this.bytCmd.length + 4 + bytToAdd.length;
byte[] bytRet = new byte[len_dest];
byte[] bytAddLen = int2byte(bytToAdd.length);
System.arraycopy(this.bytCmd, 0, bytRet, 0, this.bytCmd.length);
System.arraycopy(bytAddLen, 0, bytRet, this.bytCmd.length, 4);
System.arraycopy(bytToAdd, 0, bytRet, this.bytCmd.length + 4, bytToAdd.length);
this.bytCmd = bytRet;
} catch (Exception e) {
}
}
private byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);
targets[1] = (byte) ((res >> 8) & 0xff);
targets[2] = (byte) ((res >> 16) & 0xff);
targets[3] = (byte) (res >>> 24);
return targets;
}
public String getsResponse() {
return sResponse;
}
public void setsResponse(String sResponse) {
this.sResponse = sResponse;
}
public String getJsonstr() {
return jsonstr;
}
public void setJsonstr(String jsonstr) {
this.jsonstr = jsonstr;
}
public void clear() {
TransId = "";
CmdCode = "";
setJsonstr("");
sResponse = "null";
bytCmd = new byte[0];
}
}
package com.yl8timer.kqj.yl8timer.entity;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import cn.hutool.json.JSONUtil;
public class Device {
private String DevId;
private String fk_name;
private String fk_time;
private DeviceInfo devInfo;
private String fk_info;
//未执行命令
public Queue<Command> queue = new LinkedList<Command>();
//等待结果命令
public Map<String,Command> cmd = new HashMap<String,Command>();
///在线设备
public static Map<String,Device> devs = new HashMap<String,Device>();
public Device() {
}
public static Device addDevice(String devId,String devstr) {
Device dev = JSONUtil.toBean(devstr, Device.class);
if(devs.containsKey(devId)){
Device devr = devs.get(devId);
devr.setFk_time(dev.getFk_time());
return devr;
}else{
dev.setDevId(devId);
dev.devInfo = JSONUtil.toBean(dev.fk_info, DeviceInfo.class);
devs.put(devId,dev);
}
return dev;
}
public static int transnum = 1;
public boolean addCmd(String cmd,String sCmdParam, String transId) {
// Command cmd1 = new Command("" + transnum++, cmd, null, "OK");
Command cmd1 = new Command(transId, cmd, null, "OK");
cmd1.setBytCmd(sCmdParam);
return queue.offer(cmd1);
}
public boolean addCmd(String cmd,byte[] bytCmd, String transId) {
// Command cmd1 = new Command("" + transnum++, cmd, null, "OK");
Command cmd1 = new Command(transId, cmd, null, "OK");
cmd1.setBytCmd(bytCmd);
return queue.offer(cmd1);
}
public static Device getDevice(String DevId) {
if(devs.containsKey(DevId)){
Device devr = devs.get(DevId);
return devr;
}
return null;
}
public Command getCmd(){
try {
Command c = queue.remove();
return c;
} catch (Exception e) {
}
return new Command("","", new byte[0],"ERROR_NO_CMD");
}
public Device(String devId, String fk_name, String fk_time, String fk_info) {
DevId = devId;
this.fk_name = fk_name;
this.fk_time = fk_time;
this.fk_info = fk_info;
}
public String getDevId() {
return DevId;
}
public void setDevId(String devId) {
DevId = devId;
}
public String getFk_name() {
return fk_name;
}
public void setFk_name(String fk_name) {
this.fk_name = fk_name;
}
public String getFk_time() {
return fk_time;
}
public void setFk_time(String fk_time) {
this.fk_time = fk_time;
}
public String getFk_info() {
return fk_info;
}
public void setFk_info(String fk_info) {
this.fk_info = fk_info;
}
// {"fk_name":"HUSOON_BS","fk_time":"20191221165759","fk_info":{"supported_enroll_data":["FACE","FP","PASSWORD","IDCARD"],"fk_bin_data_lib":"FKDataHS101","firmware":"Fc601HS","firmware_filename":"Fc601HS","fp_data_ver":112,"face_data_ver":100}}
}
package com.yl8timer.kqj.yl8timer.entity;
public class DeviceInfo {
private String[] supported_enroll_data;
private String fk_bin_data_lib;
private String firmware;
private String firmware_filename;
private int fp_data_ver;
private int face_data_ver;
public String[] getSupported_enroll_data() {
return supported_enroll_data;
}
public void setSupported_enroll_data(String[] supported_enroll_data) {
this.supported_enroll_data = supported_enroll_data;
}
public String getFk_bin_data_lib() {
return fk_bin_data_lib;
}
public void setFk_bin_data_lib(String fk_bin_data_lib) {
this.fk_bin_data_lib = fk_bin_data_lib;
}
public String getFirmware() {
return firmware;
}
public void setFirmware(String firmware) {
this.firmware = firmware;
}
public String getFirmware_filename() {
return firmware_filename;
}
public void setFirmware_filename(String firmware_filename) {
this.firmware_filename = firmware_filename;
}
public int getFp_data_ver() {
return fp_data_ver;
}
public void setFp_data_ver(int fp_data_ver) {
this.fp_data_ver = fp_data_ver;
}
public int getFace_data_ver() {
return face_data_ver;
}
public void setFace_data_ver(int face_data_ver) {
this.face_data_ver = face_data_ver;
}
}
\ No newline at end of file
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Arrays;
public class EnrollData {
public EnrollData()
{
BackupNumber = -1;
bytData = new byte[0];
}
public EnrollData(int anBackupNumber, byte[] abytData)
{
BackupNumber = -1;
if (anBackupNumber >= 0)
{
BackupNumber = anBackupNumber;
if (abytData.length > 0)
{
bytData = new byte[abytData.length];
bytData = Arrays.copyOf(abytData, abytData.length);
}
}else
bytData = new byte[0];
}
public boolean IsValid()
{
if (BackupNumber < 0)
return false;
if (bytData.length < 1)
return false;
return true;
}
private int BackupNumber;
private byte [] bytData;
public int getBackupNumber() {
return BackupNumber;
}
public void setBackupNumber(int backupNumber) {
BackupNumber = backupNumber;
}
public byte[] getBytData() {
return bytData;
}
public void setBytData(byte[] bytData) {
this.bytData = bytData;
}
}
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Arrays;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
public class FKDataHS100_GLog {
public static final int STRUCT_SIZE = 12; // sizeof(GLOG_DATA_CIF11)
public byte Vaild; //must be 1
public byte IoMode;
public byte VerifyMode;
private int Year;
private byte Month;
private byte Day;
private byte Hour;
private byte Minute;
public byte BackupNumber;
public byte Second;
public int UserId;
public FKDataHS100_GLog()
{
Vaild = 0;
UserId = 0;
BackupNumber = 0;
//IoMode = 0;
//VerifyMode = 0;
Second = 0;
// tmMode = new BitVector32(0);
// tmLog = new BitVector32(0);
}
public FKDataHS100_GLog(byte[] abytLog)
{
if (abytLog.length != STRUCT_SIZE)
return;
Vaild = abytLog[0];
short tmMode = MyUtil.byte2Short(Arrays.copyOfRange(abytLog,1,3));
VerifyMode = (byte) (tmMode & 0x3f);
IoMode = (byte) ((tmMode & 0xc0) >> 6);
Second = abytLog[3];
UserId = MyUtil.byte2int(Arrays.copyOfRange(abytLog, 4, 8));
int tmLog = MyUtil.byte2int(Arrays.copyOfRange(abytLog,8,12));
Year = (tmLog & 0xfff);
Month = (byte) ((tmLog & 0xf000) >> 12);
Day = (byte) ((tmLog & 0x1f0000) >> 16);
Hour = (byte) ((tmLog & 0x3e00000) >> 21);
Minute = (byte) ((tmLog & 0xfc000000) >> 26);
}
public boolean IsValidIoTime()
{
if (Year < 1900 || Year > 3000)
return false;
if (Month < 1 || Month > 12)
return false;
if (Day < 1 || Day > 31)
return false;
if (Hour < 0 || Hour > 24)
return false;
if (Minute < 0 || Minute > 60)
return false;
if (Second < 0 || Second > 60)
return false;
return true;
}
public String GetIoTimeString()
{
if (!IsValidIoTime())
return "1970-1-1 0:0:0";
return (Year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second);
}
public byte[] GetLogData()
{
byte[] abytLog = new byte[12];
abytLog[0] = 1;
abytLog[1] = (byte) ((IoMode<<6) | (VerifyMode));
abytLog[2] = 0;
abytLog[3] = Second;
System.arraycopy(MyUtil.int2byte(UserId),0,abytLog,4,4);
int tmlog = (Year) | (Month<<12) | (Day<<16) | (Hour<<21) | (Minute<<26);
System.arraycopy(MyUtil.int2byte(tmlog), 0, abytLog, 8, 4);
return abytLog;
}
//{ Log InOut Mode Constant
public static final int IO_MODE_OUT = 0;
public static final int IO_MODE_IN = 1;
//}
public static String GetInOutModeString(int aIoMode)
{
String sRet = "";
switch (aIoMode)
{
case IO_MODE_IN:
sRet = "IN";
break;
case IO_MODE_OUT:
sRet = "OUT";
break;
default:
break;
}
return sRet;
}
//{ Log Verify Mode Constant
// public final int VERIFY_MODE_FP = 1;
public static final int LOG_FPVERIFY = 0x01; //Fp Verify
public static final int LOG_PASSVERIFY =0x02; //Pass Verify
public static final int LOG_CARDVERIFY =0x03; //Card Verify
public static final int LOG_FPPASS_VERIFY =0x04; //Pass+Fp Verify
public static final int LOG_FPCARD_VERIFY =0x05; //Card+Fp Verify
public static final int LOG_PASSFP_VERIFY =0x06; //Pass+Fp Verify
public static final int LOG_CARDFP_VERIFY =0x07; //Card+Fp Verify
public static final int LOG_JOB_NO_VERIFY =0x08; //Job number Verify
public static final int LOG_CARDPASS_VERIFY =0x09; //Card+Pass Verify
public static final int LOG_PASSCARD_VERIFY =0x89; //Pass+Card Verify
/*public static final int VERIFY_MODE_PASSWORD = 2;
public static final int VERIFY_MODE_IDCARD = 3;
public static final int VERIFY_MODE_FP_PASSWORD = 4;
public static final int VERIFY_MODE_FP_IDCARD = 5;
public static final int VERIFY_MODE_PASSWORD_FP = 6;
public static final int VERIFY_MODE_IDCARD_FP = 7;
public static final int VERIFY_MODE_FACE = 20;
public static final int VERIFY_MODE_FACE_IDCARD = 21;
public static final int VERIFY_MODE_FACE_PASSWORD = 22;
public static final int VERIFY_MODE_IDCARD_FACE = 23;
public static final int VERIFY_MODE_PASSWORD_FACE = 24;*/
//}
public static String GetVerifyModeString(int aVerifyMode)
{
String sRet = "";
switch (aVerifyMode)
{
case LOG_FPVERIFY:
sRet = "[\"FP\"]";
break;
case LOG_PASSVERIFY:
sRet = "[\"PASSWORD\"]";
break;
case LOG_CARDVERIFY:
sRet = "[\"IDCARD\"]";
break;
case LOG_FPPASS_VERIFY:
sRet = "[\"FP\",\"PASSWORD\"]";
break;
case LOG_FPCARD_VERIFY:
sRet = "[\"FP\",\"IDCARD\"]";
break;
case LOG_PASSFP_VERIFY:
sRet = "[\"PASSWORD\",\"FP\"]";
break;
case LOG_CARDFP_VERIFY:
sRet = "[\"IDCARD\",\"FP\"]";
break;
case LOG_JOB_NO_VERIFY:
sRet = "[\"JOB NO\"]";
break;
case LOG_CARDPASS_VERIFY:
sRet = "[\"IDCARD\",\"PASSWORD\"]";
break;
case LOG_PASSCARD_VERIFY:
sRet = "[\"PASSWORD\",\"IDCARD\"]";
break;
/* case VERIFY_MODE_PASSWORD_FACE:
sRet = "[\"PASSWORD\",\"FACE\"]";
break;
case VERIFY_MODE_IDCARD_FACE:
sRet = "[\"IDCARD\",\"FACE\"]";
break;*/
default:
break;
}
return sRet;
}
}
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Arrays;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
public class FKDataHS100_UserIdInfo {
public int UserId;
public byte Privilege;
public byte Enabled;
public byte BackupNumber;
public static final int STRUCT_SIZE = 8; // sizeof(USER_ID_CIF11)
//{ Backup number constant
public static final int BACKUP_FP_0 = 0; // Finger 0
public static final int BACKUP_FP_1 = 1; // Finger 1
public static final int BACKUP_FP_2 = 2; // Finger 2
public static final int BACKUP_FP_3 = 3; // Finger 3
public static final int BACKUP_FP_4 = 4; // Finger 4
public static final int BACKUP_FP_5 = 5; // Finger 5
public static final int BACKUP_FP_6 = 6; // Finger 6
public static final int BACKUP_FP_7 = 7; // Finger 7
public static final int BACKUP_FP_8 = 8; // Finger 8
public static final int BACKUP_FP_9 = 9; // Finger 9
public static final int BACKUP_PSW = 10; // Password
public static final int BACKUP_CARD = 11; // Card
//}
public FKDataHS100_UserIdInfo()
{
UserId = 0;
Privilege = 0;
Enabled = 0;
BackupNumber = 0;
/*PasswordFlag = 0;
CardFlag = 0;
FaceFlag = 0;
FpCount = 0;
VeinCount = 0;
flagEnrolled = new BitVector32(0);*/
}
public FKDataHS100_UserIdInfo(byte[] abytUserIdInfo)
{
if (abytUserIdInfo.length != STRUCT_SIZE)
return;
Enabled = abytUserIdInfo[0];
Privilege = abytUserIdInfo[1];
BackupNumber = abytUserIdInfo[2];
UserId = MyUtil.byte2int(Arrays.copyOfRange(abytUserIdInfo, 4, 8));
/*Privilege = abytUserIdInfo[4];
Enabled = abytUserIdInfo[5];
flagEnrolled = new BitVector32(BitConverter.ToInt16(abytUserIdInfo, 6));*/
}
public byte[] GetUserIdInfo()
{
byte[] abytUserIdInfo = new byte[8];
abytUserIdInfo[0] = Enabled;
abytUserIdInfo[1] = Privilege;
abytUserIdInfo[2] = BackupNumber;
System.arraycopy(MyUtil.int2byte(UserId),0,abytUserIdInfo,4,4);
return abytUserIdInfo;
}
}
\ No newline at end of file
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Arrays;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
public class FKDataHS101_GLog {
public static final int STRUCT_SIZE = 12; // sizeof(GLOG_DATA_CIF11)
public int UserId;
public byte IoMode;
public byte VerifyMode;
private int Year;
private byte Month;
private byte Day;
private byte Hour;
private byte Minute;
public byte Second;
public FKDataHS101_GLog()
{
UserId = 0;
IoMode = 0;
VerifyMode = 0;
Second = 0;
}
public FKDataHS101_GLog(byte[] abytLog)
{
if (abytLog.length != STRUCT_SIZE)
return;
UserId = MyUtil.byte2int(Arrays.copyOf(abytLog, 4));
IoMode = abytLog[5];
VerifyMode = abytLog[6];
Second = abytLog[7];
int tmlog = MyUtil.byte2int(Arrays.copyOfRange(abytLog,8,12));
Year = (tmlog & 0x00000ffc) >>> 2;
Month = (byte)((tmlog & 0x0000f000) >>> 12);
Day = (byte)((tmlog & 0x001f0000) >>> 16);
Hour = (byte)((tmlog & 0x03e00000) >>> 21);
Minute = (byte)((tmlog & 0xfc000000) >>> 26);
}
public boolean IsValidIoTime()
{
if ((Year + 1900) < 1900 || (Year + 1900) > 3000)
return false;
if (Month < 1 || Month > 12)
return false;
if (Day < 1 || Day > 31)
return false;
if (Hour < 0 || Hour > 24)
return false;
if (Minute < 0 || Minute > 60)
return false;
if (Second < 0 || Second > 60)
return false;
return true;
}
public String GetIoTimeString()
{
if (!IsValidIoTime())
return "1970-1-1 0:0:0";
return ((Year + 1900) + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second);
}
public byte[] GetLogData()
{
byte[] abytLog = new byte[12];
System.arraycopy(MyUtil.int2byte(UserId),0,abytLog,0,4);
abytLog[4] = 0;
abytLog[5] = IoMode;
abytLog[6] = VerifyMode;
abytLog[7] = Second;
int tmlog = (Year<<2) | (Month<<12) | (Day<<16) | (Hour<<21) | (Minute<<26);
System.arraycopy(MyUtil.int2byte(tmlog), 0, abytLog, 8, 4);
return abytLog;
}
//{ Log InOut Mode Constant
public static final int IO_MODE_OUT = 0;
public static final int IO_MODE_IN = 1;
//}
public static String GetInOutModeString(int aIoMode)
{
String sRet = "";
switch (aIoMode)
{
case IO_MODE_IN:
sRet = "IN";
break;
case IO_MODE_OUT:
sRet = "OUT";
break;
default:
break;
}
return sRet;
}
public static final int VERIFY_MODE_FP = 1;
public static final int VERIFY_MODE_PASSWORD = 2;
public static final int VERIFY_MODE_IDCARD = 3;
public static final int VERIFY_MODE_FP_PASSWORD = 4;
public static final int VERIFY_MODE_FP_IDCARD = 5;
public static final int VERIFY_MODE_PASSWORD_FP = 6;
public static final int VERIFY_MODE_IDCARD_FP = 7;
public static final int VERIFY_MODE_FACE = 20;
public static final int VERIFY_MODE_FACE_IDCARD = 21;
public static final int VERIFY_MODE_FACE_PASSWORD = 22;
public static final int VERIFY_MODE_IDCARD_FACE = 23;
public static final int VERIFY_MODE_PASSWORD_FACE = 24;
public static String GetVerifyModeString(int aVerifyMode)
{
String sRet = "";
switch (aVerifyMode)
{
case VERIFY_MODE_FP:
sRet = "[\"FP\"]";
break;
case VERIFY_MODE_PASSWORD:
sRet = "[\"PASSWORD\"]";
break;
case VERIFY_MODE_IDCARD:
sRet = "[\"IDCARD\"]";
break;
case VERIFY_MODE_FP_PASSWORD:
sRet = "[\"FP\",\"PASSWORD\"]";
break;
case VERIFY_MODE_FP_IDCARD:
sRet = "[\"FP\",\"IDCARD\"]";
break;
case VERIFY_MODE_PASSWORD_FP:
sRet = "[\"PASSWORD\",\"FP\"]";
break;
case VERIFY_MODE_IDCARD_FP:
sRet = "[\"IDCARD\",\"FP\"]";
break;
case VERIFY_MODE_FACE:
sRet = "[\"FACE\"]";
break;
case VERIFY_MODE_FACE_PASSWORD:
sRet = "[\"FACE\",\"PASSWORD\"]";
break;
case VERIFY_MODE_FACE_IDCARD:
sRet = "[\"FACE\",\"IDCARD\"]";
break;
case VERIFY_MODE_PASSWORD_FACE:
sRet = "[\"PASSWORD\",\"FACE\"]";
break;
case VERIFY_MODE_IDCARD_FACE:
sRet = "[\"IDCARD\",\"FACE\"]";
break;
default:
break;
}
return sRet;
}
}
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Arrays;
import com.yl8timer.kqj.yl8timer.tools.MyUtil;
public class FKDataHS101_UserIdInfo {
public int UserId;
public byte Privilege;
public byte Enabled;
private byte PasswordFlag;
private byte CardFlag;
private byte FaceFlag;
private byte FpCount;
private byte VeinCount;
public final int STRUCT_SIZE = 8; // sizeof(USER_ID_CIF11)
//{ Backup number constant
public final int BACKUP_FP_0 = 0; // Finger 0
public final int BACKUP_FP_1 = 1; // Finger 1
public final int BACKUP_FP_2 = 2; // Finger 2
public final int BACKUP_FP_3 = 3; // Finger 3
public final int BACKUP_FP_4 = 4; // Finger 4
public final int BACKUP_FP_5 = 5; // Finger 5
public final int BACKUP_FP_6 = 6; // Finger 6
public final int BACKUP_FP_7 = 7; // Finger 7
public final int BACKUP_FP_8 = 8; // Finger 8
public final int BACKUP_FP_9 = 9; // Finger 9
public final int BACKUP_PSW = 10; // Password
public final int BACKUP_CARD = 11; // Card
public final int BACKUP_FACE = 12; // Face
public final int BACKUP_VEIN_0 = 20; // Vein 0
//}
public FKDataHS101_UserIdInfo()
{
UserId = 0;
Privilege = 0;
Enabled = 0;
PasswordFlag = 0;
CardFlag = 0;
FaceFlag = 0;
FpCount = 0;
VeinCount = 0;
}
public FKDataHS101_UserIdInfo(byte[] abytUserIdInfo){
if (abytUserIdInfo.length != STRUCT_SIZE)
return;
UserId = MyUtil.byte2int(Arrays.copyOf(abytUserIdInfo, 4));
Privilege = abytUserIdInfo[4];
Enabled = abytUserIdInfo[5];
short flagEnrolled = MyUtil.byte2Short(Arrays.copyOfRange(abytUserIdInfo,6,8));
PasswordFlag = (byte) (flagEnrolled & 0x1);
CardFlag = (byte) ((flagEnrolled & 0x2) >> 1);
FaceFlag = (byte) ((flagEnrolled & 0x4) >> 2);
FpCount = (byte) ((flagEnrolled & 0x78) >> 3);
VeinCount = (byte) ((flagEnrolled & 0x1f80) >> 7);
}
public void SetBackupNumberEnrolledFlag(byte[] abytEnrolledFlag){
if(abytEnrolledFlag.length < 13) return;
if (abytEnrolledFlag[BACKUP_PSW] == 1)
PasswordFlag = 1;
if (abytEnrolledFlag[BACKUP_CARD] == 1)
CardFlag = 1;
if (abytEnrolledFlag[BACKUP_FACE] == 1)
FaceFlag = 1;
int fpcnt = 0;
int k;
for (k = 0; k < 10; k++){
if (abytEnrolledFlag[BACKUP_FP_0 + k] == 1)
fpcnt++;
}
FpCount = (byte) fpcnt;
}
public byte[] GetBackupNumberEnrolledFlag()
{
byte[] abytEnrolledFlag = new byte[20];
if (PasswordFlag == 1)
abytEnrolledFlag[BACKUP_PSW] = 1;
if (CardFlag == 1)
abytEnrolledFlag[BACKUP_CARD] = 1;
if (FaceFlag == 1)
abytEnrolledFlag[BACKUP_FACE] = 1;
int fpcnt = FpCount;
int k;
for (k = 0; k < fpcnt; k++)
abytEnrolledFlag[BACKUP_FP_0 + k] = 1;
return abytEnrolledFlag;
}
public byte[] GetUserIdInfo()
{
byte[] abytUserIdInfo = new byte[8];
System.arraycopy(MyUtil.int2byte(UserId),0,abytUserIdInfo,0,4);
abytUserIdInfo[4] = Privilege;
abytUserIdInfo[5] = Enabled;
short flagEnrolled = (short) ((PasswordFlag) | (CardFlag<<1) | (FaceFlag<<2) | (FpCount<<3) | (VeinCount<<7));
System.arraycopy(MyUtil.short2byte(flagEnrolled), 0, abytUserIdInfo, 6, 2);
return abytUserIdInfo;
}
}
\ No newline at end of file
package com.yl8timer.kqj.yl8timer.entity;
import java.util.Date;
public class FKWebTransBlockData {
public int LastBlockNo;
public Date TmLastModified;
private byte[] abytBlkData;
public FKWebTransBlockData() {
LastBlockNo = 0;
TmLastModified = new Date();
abytBlkData = new byte[0];
}
public byte[] getAbytBlkData() {
return abytBlkData;
}
public void setAbytBlkData(byte[] Data) {
if (Data.length == 0)
return;
int len_dest = Data.length + abytBlkData.length;
byte[] bytTmp = new byte[len_dest];
if(!(abytBlkData.length==0))
System.arraycopy(abytBlkData, 0, bytTmp, 0, abytBlkData.length);
System.arraycopy(Data, 0, bytTmp, abytBlkData.length, Data.length);
abytBlkData = bytTmp;
}
}
/**
* <p>Title: FkData.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkData.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkData extends Model<FkData> {
private static final long serialVersionUID = -4951212143405231415L;
@TableId(type = IdType.AUTO)
private Integer id;
private String userId;
private String devId;
private String verifyMode;
private String ioMode;
private String ioTime;
private String url;
private String resultDetail;
private Integer isSuccess;
private Integer times;
}
/**
* <p>Title: FkDev.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkDev.java
* </p>
* <p>
* Description:考勤机设备厂家实体
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkDev extends Model<FkDev> {
private static final long serialVersionUID = 719585089808817651L;
@TableId(type = IdType.AUTO)
private Integer id;
private Integer orgCode;
private String devId;
private Date createdTime;
private Date updateTime;
}
/**
* <p>Title: FkCommand.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkCommand.java
* </p>
* <p>
* Description: 考勤机指令实体
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkHsRequest extends Model<FkHsRequest> {
private static final long serialVersionUID = 6646236303191811803L;
@TableId(type = IdType.AUTO)
private Integer id;
private byte[] totalByte;
private String devId;
private String command;
private Date time;
private String jsonStr;
private String status; // OK or ERROR
private Date runtimes; // 实际运行的时间
}
/**
* <p>Title: FkCommand.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkCommand.java
* </p>
* <p>
* Description: 考勤机指令实体
* </p>
*
* @author dsc
* @date 2020年5月6日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkHsResponse extends Model<FkHsResponse> {
private static final long serialVersionUID = 6668462572456938491L;
@TableId(type = IdType.AUTO)
private Integer id;
private String devId;
private String command;
private String transId;
private Date time;
private byte[] totalByte;
}
/**
* <p>Title: FkTaskRelation.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkTaskRelation.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkTask extends Model<FkTask> {
private static final long serialVersionUID = -726688595225970379L;
@TableId(type = IdType.AUTO)
private Integer id;
private String oldDevId;
private String newDevId;
private Date createdTime;
private Date successTime;
private Integer status; // 0-无 1-执行中 2-执行完成
}
/**
* <p>Title: FkTask.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <p>
* Title: FkTask.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月14日
* @version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FkTaskRelation extends Model<FkTaskRelation> {
private static final long serialVersionUID = 8391125500173446845L;
@TableId(type = IdType.AUTO)
private Integer id;
private Integer taskId;
private String userId;
private String getTransId;
private String setTransId;
// private Integer status; // 0-无 1-执行中 2-执行完成
//
// private Date createdTime;
//
// private Date successTime;
}
/**
* <p>Title: FkUserData.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.entity.fk;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
/**
* <p>Title: FkUserData.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
public class FkUserData extends Model<FkUserData>{
private static final long serialVersionUID = 6328673173547209192L;
@TableId(type = IdType.AUTO)
private Integer id;
}
package com.yl8timer.kqj.yl8timer.tools;
import java.util.Hashtable;
import java.util.Map;
import com.yl8timer.kqj.yl8timer.entity.FKWebTransBlockData;
public class Constant {
public static Map<String, FKWebTransBlockData> Application = new Hashtable<String, FKWebTransBlockData>();
// 询问有没有对自己发送的指令
public final static String REQ_CODE_RECV_CMD = "receive_cmd";
// 表示机器向服务器上传指令执行结果
public final static String REQ_CODE_SEND_CMD_RESULT = "send_cmd_result";
// 实时出入(打卡) 记录传输
public final static String REQ_CODE_REALTIME_GLOG = "realtime_glog";
// 实时登记数据传输
public final static String REQ_CODE_REALTIME_ENROLL = "realtime_enroll_data";
public final static String LAST_UPDATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public final static String OFFLINE_TIME = "offlineTime";
public final static String OFFLINE_CHECK_TIME = "offlineCheckTime";
////user_privilege 用户权限
public final static String user_privilege_USER = "USER";
public final static String user_privilege_MANAGER = "MANAGER";
}
/**
* <p>Title: SmController.java</p>
* <p>Description: </p>
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
package com.yl8timer.kqj.yl8timer.tools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yl8timer.kqj.yl8timer.entity.Command;
import com.yl8timer.kqj.yl8timer.entity.Device;
import com.yl8timer.kqj.yl8timer.entity.EnrollData;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS100_GLog;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS100_UserIdInfo;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS101_GLog;
import com.yl8timer.kqj.yl8timer.entity.FKDataHS101_UserIdInfo;
import com.yl8timer.kqj.yl8timer.entity.FKWebTransBlockData;
import com.yl8timer.kqj.yl8timer.entity.fk.FkData;
import com.yl8timer.kqj.yl8timer.entity.fk.FkDev;
import com.yl8timer.kqj.yl8timer.entity.fk.FkHsRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
* <p>
* Title: HSTools.java
* </p>
* <p>
* Description:
* </p>
*
* @author dsc
* @date 2020年5月8日
* @version 1.0
*/
@RestController
public class HSTools {
@Value("${config.timer.url}")
private String url;
public byte[] bytRequestBin;
public byte[] bytRequestTotal;
@Autowired
public HttpServletResponse response;
@Autowired
public HttpServletRequest request;
public LogUtil log;
// private String serverUrl = "http://192.168.4.222:8089";// 对应8小时 考勤接口
private String defPath = "E:\\ylwork\\zwj\\f";
private String defimgPath = "E:\\ylwork\\zwjimg\\";
// 设置指纹,用户
private boolean ConvertEnrollDataInCmdParamBin(LogUtil log, Device dev, Command cmd) {
final String csFuncName = "ConvertEnrollDataInCmdParamBin";
log.i(csFuncName, "1 - ");
try {
JSONObject jobjDevInfo = new JSONObject(dev.getFk_info());
int DstFpDataVer = jobjDevInfo.getInt("fp_data_ver");
log.i(csFuncName, "1 - 1 - FpDataVer=" + DstFpDataVer);
// 机器采用的指纹数据版本
if (DstFpDataVer < 1 || DstFpDataVer > 10000) {
// 版本错误
return false;
}
Command innerCmd = new Command();
String sCmdParam = GetStringFromBSCommBuffer(cmd.getBytCmd());
if (sCmdParam.length() == 0) {
log.e(csFuncName, "2 - 1.1 - ");
return false;
}
JSONObject jobjCmdParam = new JSONObject(sCmdParam);
// 远程进入 录入页面
if (cmd.getCmdCode().equals("SET_ENROLL_DATA")) {
log.i(csFuncName, "2 - 2 - ");
int bkNo = jobjCmdParam.getInt("backup_number");
if (bkNo > 9) {
log.i(csFuncName, "2 - 2.1 - ");
return true;
}
log.i(csFuncName, "2 - 3 - ");
byte[] bytFpData = GetBinDataFromBSCommBinData(1, cmd.getBytCmd());
if (bytFpData.length == 0) {
log.e(csFuncName, "2 - 3.1 - ");
return false;
}
log.i(csFuncName, "2 - 4 - DstFpDataVer :" + DstFpDataVer);
innerCmd.clear();
innerCmd.setBytCmd(sCmdParam);
innerCmd.appendBinData(bytFpData);
log.i(csFuncName, "2 - 6 - ");
return true;
} else if (cmd.getCmdCode().equals("SET_USER_INFO")) {
int k, m;
log.i(csFuncName, "3 - 2 - ");
List<EnrollData> listEnrollData = new ArrayList<EnrollData>();
String user_id;
String user_name;
String user_privilege;
byte[] user_photo = new byte[0];
try {
user_id = jobjCmdParam.getStr("user_id");
user_name = jobjCmdParam.getStr("user_name");
user_privilege = jobjCmdParam.getStr("user_privilege");
if (!jobjCmdParam.isNull("user_photo")) {
log.i(csFuncName, "3 - 3 - ");
String sTemp;
sTemp = jobjCmdParam.getStr("user_photo");
m = Integer.parseInt(sTemp.substring(4, sTemp.length()));
if (m >= 1)
user_photo = GetBinDataFromBSCommBinData(m, cmd.getBytCmd());
}
log.i(csFuncName, "3 - 4 - ");
EnrollData ed;
JSONObject jobjOneED;
if (jobjCmdParam.containsKey("enroll_data_array") && !jobjCmdParam.isNull("enroll_data_array")) {
JSONArray jarrEnrollData = jobjCmdParam.getJSONArray("enroll_data_array");
for (k = 0; k < jarrEnrollData.size(); k++) {
String sTemp;
byte[] bytTemp;
jobjOneED = jarrEnrollData.getJSONObject(k);
ed = new EnrollData();
ed.setBackupNumber(Integer.parseInt(jobjOneED.getStr("backup_number")));
log.i(csFuncName, "3 - 5 - k=" + k);
sTemp = jobjOneED.getStr("enroll_data");
if (sTemp.length() < 5) {
log.e(csFuncName, "3 - 5.1 - k=" + k);
return false;
}
log.i(csFuncName, "3 - 6 - k=" + k);
m = Integer.parseInt(sTemp.substring(4));
if (m < 1) {
log.e(csFuncName, "3 - 6.1 - k=" + k);
return false;
}
log.i(csFuncName, "3 - 7 - k=" + k + " m=" + m);
bytTemp = GetBinDataFromBSCommBinData(m, cmd.getBytCmd());
ed.setBytData(bytTemp);
listEnrollData.add(ed);
}
}
} catch (Exception ex) {
log.e(csFuncName, "3 - except - " + ex.toString());
return false;
}
log.i(csFuncName, "3 - 11 - ");
if (listEnrollData.size() == 0) {
log.i(csFuncName, "3 - 11 - 1");
return true;
}
log.i(csFuncName, "3 - 12 - ");
JSONObject jobjCmdParamNew = new JSONObject();
jobjCmdParamNew.put("user_id", user_id);
jobjCmdParamNew.put("user_name", user_name);
jobjCmdParamNew.put("user_privilege", user_privilege);
log.i(csFuncName, "3 - 13 - ");
JSONArray jarrED = new JSONArray();
EnrollData ed1 = null;
m = 1;
for (k = 0; k < listEnrollData.size(); k++) {
JSONObject jobjOneED = new JSONObject();
ed1 = listEnrollData.get(k);
jobjOneED.put("backup_number", ed1.getBackupNumber());
String sTemp = "BIN_" + m;
jobjOneED.put("enroll_data", sTemp);
jarrED.put(jobjOneED);
m++;
}
jobjCmdParamNew.put("enroll_data_array", jarrED);
log.i(csFuncName, "3 - 14 - ");
if (user_photo.length > 0)
jobjCmdParamNew.put("user_photo", "BIN_" + m);
log.i(csFuncName, "3 - 15 - ");
sCmdParam = jobjCmdParamNew.toString();
innerCmd.setBytCmd(sCmdParam);
for (k = 0; k < listEnrollData.size(); k++) {
ed1 = listEnrollData.get(k);
log.i(csFuncName, "3 - 15.2 - size = " + ed1.getBytData().length);
cmd.appendBinData(ed1.getBytData());
}
log.i(csFuncName, "3 - 16 - ");
if (user_photo.length > 0)
cmd.appendBinData(user_photo);
log.i(csFuncName, "3 - 17 - ");
return true;
} else {
log.i(csFuncName, "3 - 18 - ");
return true;
}
} catch (Exception e) {
log.e(csFuncName, "Except - 2 - " + e.toString());
return false;
}
}
// 实时登记数据
public String OnRealtimeEnrollData(String asDevId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------2--------------------");
final String csFuncName = "Page_Load - realtime_enroll_data";
String sRequest;
String sResponse;
byte[] bytRequest = abytRequest;
try {
log.i(csFuncName, "1");
sRequest = GetStringFromBSCommBuffer(bytRequest);
if (sRequest.length() == 0) {
return "ERROR";
}
log.i(csFuncName, "2");
JSONObject jobjRequest = new JSONObject(sRequest);
log.i(csFuncName, "jjjjjjjjjjjj:" + sRequest);
String sUserId = jobjRequest.getStr("user_id");
log.i(csFuncName, "3");
BufferedOutputStream bos = null;
FileOutputStream fos = null;
FileWriter fw = null;
try {
// fw=new FileWriter("E:\\ylwork\\ab3.txt");
// fw.write(new String(bytRequest));
// fos = new FileOutputStream(new File(defPath + sUserId));
// bos = new BufferedOutputStream(fos);
// bos.write(bytRequest);
// JSONObject vResultJson = new JSONObject();
// vResultJson.put("asDevId", asDevId);
// vResultJson.put("asUserId", sUserId);
// vResultJson.put("abytUserData",bytRequest);
// String sFinal = vResultJson.toString();
// String url = serverUrl+"/kqz/sauserregdata";
// HttpHeaders headers = new HttpHeaders();
// MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
// params.add("json", sFinal);
// RestTemplate restTemplate = new RestTemplate();
// HttpEntity httpEntity = new HttpEntity(params, headers);
// restTemplate.postForEntity(url, httpEntity, String.class);
sResponse = "OK";
} catch (Exception ex) {
sResponse = "ERROR_DB_ACCESS";
} finally {
if (bos != null)
bos.close();
if (fos != null)
fos.close();
if (fw != null)
fw.close();
}
log.i(csFuncName, "OnRealtimeEnrollData sResponse :" + sResponse);
response.addHeader("response_code", sResponse);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
log.i(csFuncName, "4");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return "ERROR";
}
return "OK";
}
// 实时打卡数据
public void OnRealtimeGLog(String asDevId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------3--------------------");
final String csFuncName = "Page_Load - realtime_glog";
String sRequest = "";
String sResponse;
byte[] bytRequest = abytRequest;
byte[] bytLogImage = new byte[0];
try {
log.i(csFuncName, "1------------------>");
Command cmd = new Command();
GetStringAnd1stBinaryFromBSCommBuffer(bytRequest, cmd);
sRequest = cmd.getJsonstr();
bytLogImage = cmd.getBytCmd();
System.err.println("sQequest:" + sRequest);
if (sRequest.length() == 0) {
log.e(csFuncName, "1-- length=" + sRequest.length());
return;
}
log.i(csFuncName, "2");
String sUserId;
String sVerifyMode;
String sIOMode;
String sIOTime;
// String sLogImg;
String sFKBinDataLib;
JSONObject jobjRequest = new JSONObject(sRequest);
log.i(csFuncName, "2-1");
try {
sFKBinDataLib = jobjRequest.getStr("fk_bin_data_lib");
} catch (Exception e) {
log.e(csFuncName, "2-- sFKBinDataLib.length=0");
response.addHeader("response_code", "ERROR_INVALID_LIB_NAME");
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
return;
}
log.i(csFuncName, "2-2");
sUserId = jobjRequest.getStr("user_id");
sVerifyMode = jobjRequest.getStr("verify_mode");
sIOMode = jobjRequest.getStr("io_mode");
sIOTime = jobjRequest.getStr("io_time");
log.i(csFuncName, "2-3");
log.i(csFuncName, "2" + "user_id = " + sUserId + " sIOTime = " + sIOTime);
if (sFKBinDataLib == "FKDataHS101") {
sIOMode = FKDataHS101_GLog.GetInOutModeString(Integer.parseInt(sIOMode));
sVerifyMode = FKDataHS101_GLog.GetVerifyModeString(Integer.parseInt(sVerifyMode));
}
else if (sFKBinDataLib == "FKDataHS100") {
sIOMode = FKDataHS100_GLog.GetInOutModeString(Integer.parseInt(sIOMode));
sVerifyMode = FKDataHS100_GLog.GetVerifyModeString(Integer.parseInt(sVerifyMode));
}
log.i(csFuncName, "3");
sResponse = InsertRealtimeGLog(log, asDevId, sUserId, sVerifyMode, sIOMode, sIOTime, bytLogImage);
response.addHeader("response_code", sResponse);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", "0");
response.flushBuffer();
log.i(csFuncName, "4");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return;
}
}
// 实时打卡数据保存 TODO url参数
public String InsertRealtimeGLog(LogUtil log, String asDevId, String asUserId, String asVerifyMode, String asIOMode,
String asIOTime, byte[] abytLogImage) {
final String csFuncName = "InsertRealtimeGLog";
String sStdIoTime = MyUtil.ConvertFKTimeToNormalTimeString(asIOTime);
log.i(csFuncName, "1 - " + sStdIoTime);
try {
log.i(csFuncName, "2");
if (!MyUtil.isValidEngDigitString(asUserId))
return "ERROR_INVALID_USER_ID";
if (MyUtil.IsNullOrEmptyString(asVerifyMode))
return "ERROR_INVALID_VERIFY_MODE";
if (MyUtil.IsNullOrEmptyString(asIOMode))
return "ERROR_INVALID_IO_MODE";
if (!MyUtil.IsValidTimeString(sStdIoTime))
return "ERROR_INVALID_IO_TIME";
} catch (Exception e) {
log.e(csFuncName, "2 - error");
return "ERROR_INVALID_LOG";
}
try {
log.i(csFuncName, "3");
log.i(csFuncName, "4");
// String strSql;
// strSql = "INSERT INTO kqjg_realtime_glog";
// strSql = strSql + "(update_time, device_id, user_id, verify_mode, io_mode,
// io_time)VALUES('";
// strSql = strSql + TimeToString(new Date()) + "',?,?,?,?,?)";
// String[] params = new
// String[]{asDevId,asUserId,asVerifyMode,asIOMode,sStdIoTime};
// DBUtil.update(strSql, params);
/***********************************************************
* 考勤机打卡---开始
********************************************************************************************/
// KqjgRealtimeGlog glog = KqjgRealtimeGlog.builder().build();
// glog.setUpdateTime(TimeToString(new Date()));
// glog.setDeviceId(asDevId);
// glog.setUserId(asUserId);//打卡用户id
// glog.setVerifyMode(asVerifyMode);//打卡方式 1:指纹 20:人脸
// glog.setIoMode(asIOMode);
// glog.setIoTime(sStdIoTime);//打卡时间
// glog.insertOrUpdate();
// TODO
/*********************************************************************
* 考勤机打卡---结束
********************************************************************************************/
// final String uri = serverUrl+"/kqz/punchclock/" + asDevId + "/" + asUserId + "/" + asVerifyMode
// + "/0/" + sStdIoTime;
// RestTemplate restTemplate = new RestTemplate();
// String result = restTemplate.getForObject(uri, String.class);
FkData fkDataDB = FkData.builder().build().selectOne(
new LambdaQueryWrapper<FkData>().eq(FkData::getDevId, asDevId).eq(FkData::getIoTime, asIOTime));
FkData fkData = new FkData();
if (fkDataDB == null) {
fkData.setDevId(asDevId);
fkData.setUserId(asUserId);
fkData.setVerifyMode(asVerifyMode);
fkData.setIoMode(asIOMode);
fkData.setIoTime(sStdIoTime);
fkData.setUrl(url);
fkData.setTimes(1);
fkData.setIsSuccess(0);
fkData.insert();
}
JSONObject vResultJson = new JSONObject();
vResultJson.put("dev_id", asDevId);
vResultJson.put("user_id", asUserId);
vResultJson.put("verify_mode", asVerifyMode);
vResultJson.put("io_time", sStdIoTime);
String sFinal = vResultJson.toString();
ResponseEntity<String> request = null;
try {
// String url = serverUrl + "/kqz/punchclock";
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("json", sFinal);
RestTemplate restTemplate = new RestTemplate();
HttpEntity httpEntity = new HttpEntity(params, headers);
System.err.println("url:" + url);
request = restTemplate.postForEntity(url, httpEntity, String.class);
} catch (Exception e) {
return "OK";
}
System.err.println(request.getBody());
String requestBody = request.getBody();
JSONObject jsonObject = JSONUtil.parseObj(requestBody);
fkData.setResultDetail(jsonObject.toString());
if (jsonObject.getStr("code").equals("200")) {
fkData.setIsSuccess(1);
}
fkData.insertOrUpdate();
log.i(csFuncName, "5");
if (SaveLogImageToFile(log, asDevId, asUserId, asIOTime, abytLogImage) != 0) {
log.e(csFuncName, "Error to save log image");
return "ERROR_SAVE_LOG_IMAGE";
}
log.i(csFuncName, "6");
return "OK";
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.getMessage());
return "ERROR_DB_ACCESS";
}
}
// 保存图片
private int SaveLogImageToFile(LogUtil log, String asDevId, String asUserId, String asIOTime, byte[] abytLogImage) {
final String csFuncName = "SaveLogImageToFile";
String sLogImgFolder;
try {
log.i(csFuncName, "0");
if (abytLogImage.length < 1)
return 0;
log.i(csFuncName, "2");
// config
File f = new File(defimgPath);
sLogImgFolder = f.getParentFile().getAbsolutePath() + File.separator + asIOTime.substring(0, 8);
f = new File(sLogImgFolder);
if (!f.exists())
f.mkdir();
log.i(csFuncName, "3 - " + sLogImgFolder);
FileOutputStream fs = new FileOutputStream(
sLogImgFolder + File.separator + asUserId + "_" + asIOTime + ".jpg");
fs.write(abytLogImage, 0, abytLogImage.length);
fs.flush();
fs.close();
log.i(csFuncName, "4");
return 0;
} catch (Exception ex) {
log.e(csFuncName, "Except - " + ex.getMessage());
return -100;
}
}
public void OnSendCmdResult(String asDevId, String sTransId, byte[] abytRequest, HttpServletResponse response,
HttpServletRequest request) {
Logoutput("--------------------4--------------------");
final String csFuncName = "Page_Load - send_cmd_result";
byte[] bytCmdResult = abytRequest;
String sReturnCode;
log.i(csFuncName, "1");
try {
log.i(csFuncName, "2 - trans_id:" + sTransId);
Command cmd = new Command();
// 重启
// if (CheckResetCmd(log, asDevId, cmd)) {
// log.i(csFuncName, "2.1");
// SendResponseToClient("RESET_FK", sTransId, "", bytEmpty, response);
// return;
// }
// 取消命令
// if (IsCancelledCmd(log, asDevId, sTransId)) {
// log.i(csFuncName, "2.2");
// SendResponseToClient("ERROR_CANCELED", sTransId, "", bytEmpty, response);
// return;
// }
log.i(csFuncName, "3");
sReturnCode = request.getHeader("cmd_return_code").toString();
SetCmdResult(log, sTransId, asDevId, sReturnCode, bytCmdResult, cmd);
log.i(csFuncName, "4");
SendResponseToClient(cmd.getsResponse(), cmd.getTransId(), cmd.getCmdCode(), cmd.getBytCmd(), response);
log.i(csFuncName, "5");
} catch (Exception ex) {
log.e(csFuncName, "Except - 1 - " + ex.toString());
return;
}
}
public String OnReceiveCmd(String asDevId, String asTransId, byte[] abytRequest, HttpServletResponse response) {
Logoutput("--------------------5--------------------");
final String csFuncName = "Page_Load - receive_cmd";
String sRequest;
byte[] bytRequest = abytRequest;
try {
log.i(csFuncName, "2");
sRequest = GetStringFromBSCommBuffer(bytRequest);
if (sRequest.length() == 0) {
FkHsRequest.builder().runtimes(new Date()).status(Command.ERROR).build()
.update(new LambdaUpdateWrapper<FkHsRequest>().eq(FkHsRequest::getDevId, asDevId)
.eq(FkHsRequest::getId, asTransId)); // 更新请求状态
return Command.ERROR;
}
Device dev = Device.addDevice(asDevId, sRequest);
log.i(csFuncName, "3 - DevName=" + dev.getFk_name() + ", DevTime=" + dev.getFk_time() + ", DevInfo="
+ dev.getFk_info());
// 检查命令
// Command cmd = new Command(sTransId, sCmdCode, new byte[0], sResponse);
// ReceiveCmd(log, dev, cmd);
Command cmd = dev.getCmd();
log.i(csFuncName, "4");
SendResponseToClient(cmd.getsResponse(), cmd.getTransId(), cmd.getCmdCode(), cmd.getBytCmd(), response);
log.i(csFuncName, "5");
FkDev.builder().updateTime(new Date()).build()
.update(new LambdaUpdateWrapper<FkDev>().eq(FkDev::getDevId, asDevId)); // 更新设备时间保持alive
} catch (Exception ex) {
log.i(csFuncName, "Except - 1 - " + ex.toString());
// ex.printStackTrace();
FkHsRequest.builder().runtimes(new Date()).status(Command.ERROR).build()
.update(new LambdaUpdateWrapper<FkHsRequest>().eq(FkHsRequest::getDevId, asDevId)
.eq(FkHsRequest::getId, asTransId)); // 更新请求状态
return Command.ERROR;
}
FkHsRequest.builder().runtimes(new Date()).status(Command.OK).build()
.update(new LambdaUpdateWrapper<FkHsRequest>().eq(FkHsRequest::getDevId, asDevId).eq(FkHsRequest::getId,
asTransId)); // 更新请求状态
return Command.OK;
}
public int GetRequestStreamBytes(HttpServletRequest request) {
Logoutput("--------------------6--------------------");
int lenContent = request.getContentLength();
if (lenContent < 1)
return 0;
InputStream streamIn;
byte[] bytRecv = new byte[lenContent];
try {
streamIn = request.getInputStream();
int lenRead = 0, readlen = 0;
while ((readlen = streamIn.read(bytRecv, lenRead, 1024)) != -1) {
lenRead += readlen;
}
// lenRead = streamIn.read(bytRecv, 0, lenContent);
if (lenRead != lenContent) {
return -1;
}
} catch (IOException e) {
e.printStackTrace();
}
bytRequestBin = bytRecv;
return lenContent;
}
public void RemoveOldBlockStream() {
Logoutput("--------------------7--------------------");
Date dtCur = new Date();
try {
List<String> listDevIdKey = new ArrayList<String>();
FKWebTransBlockData app_val_blk;
Iterator<Entry<String, FKWebTransBlockData>> iter = Constant.Application.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, FKWebTransBlockData> entry = (Map.Entry<String, FKWebTransBlockData>) iter.next();
String sKey = entry.getKey();
if (!sKey.equalsIgnoreCase("key_dev_"))
continue;
app_val_blk = entry.getValue();
if (dtCur.getTime() - app_val_blk.TmLastModified.getTime() > 1000 * 60 * 30) {
listDevIdKey.add(sKey);
}
}
for (int i = 0; i < listDevIdKey.size(); i++) {
Constant.Application.remove(listDevIdKey.get(i));
}
} catch (Exception e) {
log.e(e.getMessage());
}
}
public int GetBlockDataAndRemove(String asDevId) {
Logoutput("--------------------8--------------------");
bytRequestTotal = new byte[0];
if (asDevId.length() == 0)
return -1;
try {
String app_key;
app_key = "key_dev_" + asDevId;
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
log.i("GetBlockDataAndRemove->", "app_val_blk == null");
return 0;
}
bytRequestTotal = Arrays.copyOf(app_val_blk.getAbytBlkData(), app_val_blk.getAbytBlkData().length);
Constant.Application.remove(app_key);
return 0;
} catch (Exception e) {
return -11;
}
}
public int AddBlockData(String asDevId, int anBlkNo, byte[] abytBlkData) {
Logoutput("--------------------9--------------------");
if (asDevId.length() == 0)
return -1; // -1 :
if (anBlkNo < 1)
return -1;
if (abytBlkData.length == 0)
return -1;
try {
String app_key;
app_key = "key_dev_" + asDevId;
if (anBlkNo == 1) {
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
app_val_blk = new FKWebTransBlockData();
Constant.Application.put(app_key, app_val_blk);
} else {
Constant.Application.remove(app_key);
app_val_blk = new FKWebTransBlockData();
Constant.Application.put(app_key, app_val_blk);
}
app_val_blk.LastBlockNo = 1;
app_val_blk.setAbytBlkData(abytBlkData);
} else {
FKWebTransBlockData app_val_blk = (FKWebTransBlockData) Constant.Application.get(app_key);
if (app_val_blk == null) {
return -2;
}
if (app_val_blk.LastBlockNo != anBlkNo - 1) {
return -3;
}
app_val_blk.LastBlockNo = anBlkNo;
app_val_blk.setAbytBlkData(abytBlkData);
}
return 0;
} catch (Exception e) {
return -11;
}
}
public void SendResponseToClient(String asResponseCode, String asTransId, String asCmdCode, byte[] abytCmdParam,
HttpServletResponse response) {
Logoutput("--------------------10--------------------");
response.addHeader("response_code", asResponseCode);
response.addHeader("trans_id", asTransId);
response.addHeader("cmd_code", asCmdCode);
response.setContentType("application/octet-stream");
response.addHeader("Content-Length", String.valueOf(abytCmdParam.length));
try {
if (abytCmdParam.length > 0) {
OutputStream streamOut = response.getOutputStream();
streamOut.write(abytCmdParam, 0, abytCmdParam.length);
streamOut.close();
}
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
public String GetStringFromBSCommBuffer(byte[] abytBSComm) {
if (abytBSComm.length < 4)
return "";
try {
String sRet;
int lenText = MyUtil.byte2int(abytBSComm);
if (lenText > abytBSComm.length - 4)
return "";
if (lenText == 0)
return "";
if (abytBSComm[4 + lenText - 1] == 0) // if last value of string buufer is 0x0
sRet = MyUtil.byte2String(abytBSComm, 4, lenText - 1);
else
sRet = MyUtil.byte2String(abytBSComm, 4, lenText);
return sRet;
} catch (Exception e) {
return "";
}
}
public byte[] ConcateByteArray(byte[] abytDest, byte[] abytSrc) {
int len_dest = abytDest.length + abytSrc.length;
if (abytSrc.length == 0)
return abytDest;
byte[] bytTmp = new byte[len_dest];
System.arraycopy(abytDest, 0, bytTmp, 0, abytDest.length);
System.arraycopy(abytSrc, 0, bytTmp, abytDest.length, abytSrc.length);
return bytTmp;
}
// 更新固件
private boolean MakeUpdateFirmwareCmdParamBin(LogUtil log, String devId, String asDevInfo, Command cmd) {
final String csFuncName = "MakeUpdateFirmwareCmdParamBin";
if (!cmd.getCmdCode().equals("UPDATE_FIRMWARE"))
return true;
log.i(csFuncName, "1 - ");
FileInputStream fs = null;
try {
JSONObject jobjDevInfo = new JSONObject(asDevInfo);
final String sPrefix = jobjDevInfo.getStr("firmware_filename");
log.i(csFuncName, "2 - prefix:" + sPrefix);
// config
File f = new File("G:/Temp/BSFirmware/");
log.i(csFuncName, "3 - firmware file Dir:" + f.getAbsolutePath());
File[] FirmwareFiles = f.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.startsWith(sPrefix) && name.endsWith(".bin"))
return true;
return false;
}
});
if (FirmwareFiles == null || FirmwareFiles.length == 0) {
// String sSql = "UPDATE kqjg_fkcmd_trans SET
// return_code='ERROR_NO_FIRMWARE_FILE', status='CANCELLED', update_time = NOW()
// WHERE trans_id='" + cmd.getTransId() + "'";
// DBUtil.update(sSql, null);
// KqjgFkcmdTrans trans =
// KqjgFkcmdTrans.builder().returnCode("ERROR_NO_FIRMWARE_FILE").status("CANCELLED").updateTime(TimeToString(new
// Date())).build();
// UpdateWrapper<KqjgFkcmdTrans> userUpdateWrapper = new UpdateWrapper<>();
// userUpdateWrapper.eq("trans_id", cmd.getTransId());
// trans.update(userUpdateWrapper);
return false;
}
log.i(csFuncName, "4 - firmware file:" + FirmwareFiles[0].getName());
byte[] bytFirmwareBin = new byte[(int) FirmwareFiles[0].length()];
fs = new FileInputStream(FirmwareFiles[0]);
int offset = 0;
int numRead = 0;
while (numRead >= 0) {
if (offset < bytFirmwareBin.length)
break;
numRead = fs.read(bytFirmwareBin, offset, bytFirmwareBin.length - offset);
offset += numRead;
}
log.i(csFuncName, "5 - ");
String sFileTitle = FirmwareFiles[0].getName();
String sCmdParam = "{\"firmware_file_name\":\"" + sFileTitle + "\",\"firmware_bin_data\":\"BIN_1\"}";
cmd.setBytCmd(sCmdParam);
cmd.appendBinData(bytFirmwareBin);
return true;
} catch (Exception e) {
log.e(csFuncName, "Exception : " + e.getMessage());
return false;
} finally {
if (fs != null)
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] GetBinDataFromBSCommBinData(int anOrder, byte[] bytBSComm) {
byte[] bytEmpty = new byte[0];
try {
// Convert SQLSever Data types to C# data types
// SQLSever Data type (varbinary) <-> C# data type (byte [])
Logoutput("bytBSComm = " + bytBSComm.length);
if (bytBSComm.length < 4)
return bytEmpty;
if (anOrder < 0 || anOrder > 255)
return bytEmpty;
int orderBin;
int posBin;
int lenBin;
int lenText = MyUtil.byte2int(bytBSComm);
Logoutput("lenText = " + lenText);
if (lenText > bytBSComm.length - 4)
return bytEmpty;
posBin = 4 + lenText;
orderBin = 0;
while (true) {
Logoutput("posBin = " + posBin);
if (posBin > bytBSComm.length - 4)
return bytEmpty;
lenBin = MyUtil.byte2int(bytBSComm, posBin);
Logoutput("lenBin = " + lenBin);
Logoutput("comparelen = " + (bytBSComm.length - posBin - 4));
if (lenBin > bytBSComm.length - posBin - 4)
return bytEmpty;
orderBin++;
if (orderBin == anOrder)
break;
posBin = posBin + 4 + lenBin;
}
byte[] bytRet = new byte[lenBin];
System.arraycopy(bytBSComm, posBin + 4, bytRet, 0, lenBin);
Logoutput("bytRet = " + bytRet.length);
return bytRet;
} catch (Exception e) {
Logoutput("err");
return bytEmpty;
}
}
public void SetCmdResult(LogUtil log, String asTransId, String asDevId, String asReturnCode, byte[] abytCmdResult,
Command cmd) {
final String csFuncName = "SetCmdResult";
log.i(csFuncName, "0 - trans_id:" + asTransId + ", dev_id:" + asDevId);
log.i(csFuncName, "1");
try {
// Thread.sleep(10000);
// log.i(csFuncName, "2");
// if (SaveCmdResultLogData(log, asTransId, asDevId, abytCmdResult) == false) {
// cmd.setsResponse("ERROR_DB_SAVE_LOG");
// return;
// }
//
// if (SaveUserIdList(log, asTransId, asDevId, abytCmdResult) == false) {
// cmd.setsResponse("ERROR_DB_SAVE_USER_ID_LIST");
// return;
// }
// pstmt = sqlConn.prepareStatement("{call dbo.usp_set_cmd_result(?,?,?,?)}");
// pstmt = sqlConn.prepareStatement("call usp_set_cmd_result(?,?,?,?)");
// pstmt.setString(1, asDevId);
// pstmt.setString(2, asTransId);
// pstmt.setString(3, asReturnCode);
// pstmt.setBytes(4, abytCmdResult);
// pstmt.execute();
// kqjgfkcmdtransmapper.call(asDevId,asTransId,asReturnCode,abytCmdResult);
log.i(csFuncName, "3");
cmd.setsResponse("OK");
FkHsRequest.builder().runtimes(new Date()).status(Command.OK).build()
.update(new LambdaUpdateWrapper<FkHsRequest>().eq(FkHsRequest::getDevId, asDevId)
.eq(FkHsRequest::getId, asTransId)); // 更新请求状态
return;
} catch (Exception e) {
log.e(csFuncName, "Except - 1 - " + e.toString());
cmd.setsResponse("ERROR_DB_ACCESS");
FkHsRequest.builder().runtimes(new Date()).status(Command.ERROR).build()
.update(new LambdaUpdateWrapper<FkHsRequest>().eq(FkHsRequest::getDevId, asDevId)
.eq(FkHsRequest::getId, asTransId)); // 更新请求状态
return;
}
}
// 保存user id list
private boolean SaveUserIdList(LogUtil log, String asTransId, String asDevId, byte[] abytCmdResult) {
final String csFuncName = "SaveUserIdList";
log.i(csFuncName, "1");
log.i(csFuncName, "2" + " astrans_id = " + asTransId);
log.i(csFuncName, "3");
String sFKDataLib = "";
String sJson;
byte[] bytUserIdList;
Command cmd = new Command();
Logoutput("sFKDataLib->" + sFKDataLib);
GetStringAnd1stBinaryFromBSCommBuffer(abytCmdResult, cmd);
sJson = cmd.getJsonstr();
bytUserIdList = cmd.getBytCmd();
if (sJson.length() == 0)
return false;
Logoutput("sJson->" + sJson);
log.i(csFuncName, "4");
int cntUserId, sizeOneUserId;
try {
JSONObject jobjLogInfo = new JSONObject(sJson);
cntUserId = jobjLogInfo.getInt("user_id_count");
sizeOneUserId = jobjLogInfo.getInt("one_user_id_size");
if (bytUserIdList.length < cntUserId * sizeOneUserId)
return false;
log.i(csFuncName, "5");
if (!"FKDataHS101".equalsIgnoreCase(sFKDataLib) && !"FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
log.e(csFuncName, "error - 1");
return false;
}
if (sizeOneUserId != 8)
return false;
log.i(csFuncName, "6 - HS101");
// String sSqlTemp = "DELETE FROM " + csTblUserId + " WHERE trans_id='" +
// asTransId +
// "' AND device_id='" + asDevId + "'";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList.builder().build().delete(
// new
// QueryWrapper<KqjgFkcmdTransCmdResultUserIdList>().lambda().eq(KqjgFkcmdTransCmdResultUserIdList::getTransId,
// asTransId)
// .eq(KqjgFkcmdTransCmdResultUserIdList::getDeviceId, asDevId));
int k;
byte[] bytOneUserId = new byte[sizeOneUserId];
byte[] bytEnrolledFlag;
for (k = 0; k < cntUserId; k++) {
int nEnrollDataCount = 0;
System.arraycopy(bytUserIdList, k * sizeOneUserId, bytOneUserId, 0, sizeOneUserId);
if ("FKDataHS101".equalsIgnoreCase(sFKDataLib)) {
FKDataHS101_UserIdInfo usrid = new FKDataHS101_UserIdInfo(bytOneUserId);
String sUserId = String.valueOf(usrid.UserId);
bytEnrolledFlag = usrid.GetBackupNumberEnrolledFlag();
for (int bkn = 0; bkn < bytEnrolledFlag.length; bkn++) {
if (bytEnrolledFlag[bkn] == 1) {
nEnrollDataCount++;
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += bkn + ")";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(bkn);
// glog.insertOrUpdate();
}
}
if (nEnrollDataCount == 0) {
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += "-1)";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(-1);
// glog.insertOrUpdate();
}
} else if ("FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
FKDataHS100_UserIdInfo usrid = new FKDataHS100_UserIdInfo(bytOneUserId);
String sUserId = String.valueOf(usrid.UserId);
int BackupNumber = (int) usrid.BackupNumber;
// sSqlTemp = "INSERT INTO " + csTblUserId;
// sSqlTemp += "(trans_id, device_id, user_id, backup_number)";
// sSqlTemp += "VALUES('" + asTransId + "', '";
// sSqlTemp += asDevId + "', '";
// sSqlTemp += sUserId + "', ";
// sSqlTemp += BackupNumber + ")";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultUserIdList glog =
// KqjgFkcmdTransCmdResultUserIdList.builder().build();
// glog.setTransId(Integer.valueOf(asTransId));
// glog.setDeviceId(asDevId);
// glog.setUserId(sUserId);
// glog.setBackupNumber(BackupNumber);
// glog.insertOrUpdate();
}
}
log.i(csFuncName, "7 - HS101");
} catch (Exception ex) {
log.e(csFuncName, "error - 2 - " + ex.toString());
return false;
}
log.i(csFuncName, "8");
return true;
}
// 保存命令结果
private boolean SaveCmdResultLogData(LogUtil log, String asTransId, String asDevId, byte[] abytCmdResult) {
final String csFuncName = "SaveCmdResultLogData";
log.i(csFuncName, "3");
String sFKDataLib = "";
String sJson;
byte[] bytLogList;
Command cmd = new Command();
GetStringAnd1stBinaryFromBSCommBuffer(abytCmdResult, cmd);
sJson = cmd.getJsonstr();
bytLogList = cmd.getBytCmd();
if (sJson.length() == 0)
return false;
log.i(csFuncName, "4");
int cntLog, sizeOneLog;
try {
System.err.println("1:" + sJson);
JSONObject jobjLogInfo = new JSONObject(sJson);
System.err.println("2:" + jobjLogInfo);
// cntLog = jobjLogInfo.getInt("log_count");
// sizeOneLog = jobjLogInfo.getInt("one_log_size");
// if (bytLogList.length < cntLog * sizeOneLog) {
// return false;
// }
// log.i(csFuncName, "5 log count=" + cntLog);
if (!"FKDataHS101".equalsIgnoreCase(sFKDataLib) && !"FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
log.e(csFuncName, "error - 1");
return false;
}
// if (sizeOneLog != 12)
// return false;
log.i(csFuncName, "6 - HS101");
// String sSqlTemp = "DELETE FROM " + csTblLog + " WHERE trans_id='" + asTransId
// +
// "' AND device_id='" + asDevId + "'";
// DBUtil.update(sSqlTemp, null);
// KqjgFkcmdTransCmdResultLogData.builder().build().delete(
// new
// QueryWrapper<KqjgFkcmdTransCmdResultLogData>().lambda().eq(KqjgFkcmdTransCmdResultLogData::getTransId,
// asTransId)
// .eq(KqjgFkcmdTransCmdResultLogData::getDeviceId, asDevId));
// int k;
// byte[] bytOneLog = new byte[sizeOneLog];
// for (k = 0; k < cntLog; k++) {
// System.arraycopy(bytLogList, k * sizeOneLog, bytOneLog, 0, sizeOneLog);
// log.i("debug:", "6 - HS101 bytOneLog=" + Arrays.toString(bytOneLog));
//
// if ("FKDataHS101".equalsIgnoreCase(sFKDataLib)) {
// FKDataHS101_GLog glog = new FKDataHS101_GLog(bytOneLog);
// String sUserId = String.valueOf(glog.UserId);
// String sIoMode = FKDataHS101_GLog.GetInOutModeString(glog.IoMode);
// String sVerifyMode = FKDataHS101_GLog.GetVerifyModeString(glog.VerifyMode);
// String sIoTime = glog.GetIoTimeString();
// // sSqlTemp = "INSERT INTO " + csTblLog;
// // sSqlTemp += "(trans_id, device_id, user_id, verify_mode, io_mode, io_time)";
// // sSqlTemp += "VALUES('" + asTransId + "', '";
// // sSqlTemp += asDevId + "', '";
// // sSqlTemp += sUserId + "', '";
// // sSqlTemp += sVerifyMode + "', '";
// // sSqlTemp += sIoMode + "', '";
// // sSqlTemp += sIoTime + "')";
// // DBUtil.update(sSqlTemp, null);
// // KqjgFkcmdTransCmdResultLogData logdata =
// // KqjgFkcmdTransCmdResultLogData.builder().build();
// // logdata.setTransId(Integer.valueOf(asTransId));
// // logdata.setDeviceId(asDevId);
// // logdata.setUserId(sUserId);
// // logdata.setVerifyMode(sVerifyMode);
// // logdata.setIoMode(sIoMode);
// // logdata.setIoTime(sIoTime);
// // logdata.insertOrUpdate();
// } else if ("FKDataHS100".equalsIgnoreCase(sFKDataLib)) {
// FKDataHS100_GLog glog = new FKDataHS100_GLog(bytOneLog);
// String sUserId = String.valueOf(glog.UserId);
// String sIoMode = FKDataHS100_GLog.GetInOutModeString(glog.IoMode);
// String sVerifyMode = FKDataHS100_GLog.GetVerifyModeString(glog.VerifyMode);
// String sIoTime = glog.GetIoTimeString();
// // sSqlTemp = "INSERT INTO " + csTblLog;
// // sSqlTemp += "(trans_id, device_id, user_id, verify_mode, io_mode, io_time)";
// // sSqlTemp += "VALUES('" + asTransId + "', '";
// // sSqlTemp += asDevId + "', '";
// // sSqlTemp += sUserId + "', '";
// // sSqlTemp += sVerifyMode + "', '";
// // sSqlTemp += sIoMode + "', '";
// // sSqlTemp += sIoTime + "')";
// // DBUtil.update(sSqlTemp, null);
// // KqjgFkcmdTransCmdResultLogData logdata =
// // KqjgFkcmdTransCmdResultLogData.builder().build();
// // logdata.setTransId(Integer.valueOf(asTransId));
// // logdata.setDeviceId(asDevId);
// // logdata.setUserId(sUserId);
// // logdata.setVerifyMode(sVerifyMode);
// // logdata.setIoMode(sIoMode);
// // logdata.setIoTime(sIoTime);
// // logdata.insertOrUpdate();
// }
// }
log.i(csFuncName, "7 - HS101");
} catch (Exception ex) {
log.e(csFuncName, "error - 2 - " + ex.toString());
return false;
}
log.i(csFuncName, "8");
return true;
}
public void GetStringAnd1stBinaryFromBSCommBuffer(byte[] abytBSComm, Command cmd) {
if (abytBSComm.length < 4)
return;
try {
int lenText = MyUtil.byte2int(abytBSComm);
if (lenText > abytBSComm.length - 4)
return;
if (lenText == 0) {
cmd.setJsonstr("");
} else {
if (abytBSComm[4 + lenText - 1] == 0) // if last value of string buufer is 0x0
cmd.setJsonstr(MyUtil.byte2String(abytBSComm, 4, lenText - 1));
else
cmd.setJsonstr(MyUtil.byte2String(abytBSComm, 4, lenText));
}
int posBin = 4 + lenText;
int lenBin = MyUtil.byte2int(abytBSComm, posBin);
if (lenBin < 1)
return;
if (lenBin > abytBSComm.length - posBin - 4)
return;
cmd.setBytCmd(new byte[lenBin]);
System.arraycopy(abytBSComm, posBin + 4, cmd.getBytCmd(), 0, lenBin);
return;
} catch (Exception e) {
return;
}
}
/*******************************
* 请求方法封装
*
* @param devId
* @param jsonStr
************************************/
public boolean setUser(String devId, String jsonStr) {
Device dev = Device.getDevice(devId);
// JSONObject vResultJson = new JSONObject();
// vResultJson.put("user_id", "600119");
// vResultJson.put("user_privilege", "MANAGE");
// String jsonStr = vResultJson.toString();
String cmd = Command.SET_USER_INFO;
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(jsonStr);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
Boolean result = dev.addCmd(cmd, jsonStr, transId);
return result;
}
public boolean setUserName(String devId, String userId, String userName) {
Device dev = Device.getDevice(devId);
// String cmd = "SET_USER_NAME";
String cmd = Command.SET_USER_INFO;
FkHsRequest fkHsRequest = new FkHsRequest();
JSONObject vResultJson = new JSONObject();
vResultJson.put("user_id", userId);
vResultJson.put("user_name", userName);
String jsonStr = vResultJson.toString();
fkHsRequest.setJsonStr(jsonStr);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
Boolean result = dev.addCmd(cmd, jsonStr, transId);
System.err.println(result);
return result;
}
public boolean setPassword(String devId, String userId, String userName) {
Device dev = Device.getDevice(devId);
String cmd = "SET_USER_PASSWORD";
FkHsRequest fkHsRequest = new FkHsRequest();
JSONObject vResultJson = new JSONObject();
vResultJson.put("user_id", userId);
vResultJson.put("user_name", userName);
String jsonStr = vResultJson.toString();
fkHsRequest.setJsonStr(jsonStr);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
Boolean result = dev.addCmd(cmd, jsonStr, transId);
return result;
}
public boolean addUserPrivilege(String devId, String userId, Integer privilege) {
Device dev = Device.getDevice(devId);
JSONObject vResultJson = new JSONObject();
vResultJson.put("user_id", userId);
if (privilege == 1) {
vResultJson.put("user_privilege", Constant.user_privilege_USER); // 1-普通用户
} else if (privilege == 2) {
vResultJson.put("user_privilege", Constant.user_privilege_MANAGER); // 2-管理员
} else {
vResultJson.put("user_privilege", Constant.user_privilege_USER); // 默认普通用户
}
String jsonStr = vResultJson.toString();
String cmd = "SET_USER_PRIVILEGE";
// String cmd = Command.SET_USER_INFO;;
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(jsonStr);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
Boolean result = dev.addCmd(cmd, jsonStr, transId);
return result;
}
public boolean setTime(String devId) {
String cmd = Command.SET_TIME;
Date now = new Date();
Device dev = Device.getDevice(devId);
String jsonStr = "{\"time\":\"" + MyUtil.GetFKTimeString14(now) + "\"}";
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(jsonStr);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(now);
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
boolean result = dev.addCmd(cmd, jsonStr, transId);
return result;
}
public boolean setDeleteUser(String devId, String userId) {
String cmd = Command.DELETE_USER;
JSONObject vResultJson = new JSONObject();
Device dev = Device.getDevice(devId);
vResultJson.put("user_id", userId);
String sFinal = vResultJson.toString();
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(sFinal);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
boolean result = dev.addCmd(cmd, sFinal, transId);
return result;
}
public boolean getEnrollData(String devId, String userId, Integer number) {
String cmd = "GET_ENROLL_DATA";
JSONObject vResultJson = new JSONObject();
Device dev = Device.getDevice(devId);
vResultJson.put("user_id", userId);
vResultJson.put("backup_number", number);
String sFinal = vResultJson.toString();
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(sFinal);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
boolean result = dev.addCmd(cmd, sFinal, transId);
return result;
}
public String getUserInfo(String devId, String userId) {
String cmd = Command.GET_USER_INFO;
JSONObject vResultJson = new JSONObject();
Device dev = Device.getDevice(devId);
vResultJson.put("user_id", userId);
String sFinal = vResultJson.toString();
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setJsonStr(sFinal);
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
boolean result = dev.addCmd(cmd, sFinal, transId);
if (result != false)
return transId;
return null;
}
public String setUserInfo(String devId, byte[] byteCmd) {
String cmd = Command.SET_USER_INFO;
Device dev = Device.getDevice(devId);
FkHsRequest fkHsRequest = new FkHsRequest();
fkHsRequest.setDevId(devId);
fkHsRequest.setCommand(cmd);
fkHsRequest.setTotalByte(byteCmd);
fkHsRequest.setTime(new Date());
fkHsRequest.insert();
String transId = fkHsRequest.getId().toString();
boolean result = dev.addCmd(cmd, byteCmd, transId);
return transId;
}
@Value("${config.environmental-science}")
public String environmental_science;
public void Logoutput(String science) {
if(!("pro").equals(environmental_science)) {
System.out.println(science);
}else {
System.out.println("");
}
}
}
package com.yl8timer.kqj.yl8timer.tools;
import org.springframework.beans.factory.annotation.Value;
public class LogUtil {
private static LogUtil log = null;
private boolean isDebugMsg = false;
private LogUtil(boolean isDebugMsg){
this.isDebugMsg = isDebugMsg;
}
public static LogUtil getInstance(boolean isDebugMsg){
synchronized (LogUtil.class) {
if(log == null){
log = new LogUtil(isDebugMsg);
}
return log;
}
}
public void e(String msg){
if(isDebugMsg)
Logoutput("[Error]:"+msg);
}
public void e(String type,String msg){
if(isDebugMsg)
Logoutput("[Error]:"+type+"---->"+msg);
}
public void i(String msg){
if(isDebugMsg)
Logoutput("[info]:"+msg);
}
public void i(String type,String msg){
if(isDebugMsg)
Logoutput("[info]:"+type+"---->"+msg);
}
public void t(String tar,String msg){
if(isDebugMsg)
Logoutput("[" + tar + "]:" + msg);
}
@Value("${config.environmental-science}")
public String environmental_science;
public void Logoutput(String science) {
if(!("pro").equals(environmental_science)) {
System.out.println(science);
}else {
System.out.println("");
}
}
}
package com.yl8timer.kqj.yl8timer.tools;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyUtil {
public static boolean isValidEngDigitString(String str){
// ��֤����
String regEx = "[a-zA-Z0-9_-]{0,}";
// ����������ʽ
Pattern pattern = Pattern.compile(regEx);
// ���Դ�Сд��д��
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// �ַ����Ƿ���������ʽ��ƥ��
return matcher.matches();
}
public static String byte2String(byte[] res, int offset, int len) throws UnsupportedEncodingException{
String s = new String(res, offset, len,"UTF-8");
return s;
}
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);// ���λ
targets[1] = (byte) ((res >> 8) & 0xff);// �ε�λ
targets[2] = (byte) ((res >> 16) & 0xff);// �θ�λ
targets[3] = (byte) (res >>> 24);// ���λ,�޷������ơ�
return targets;
}
public static byte[] short2byte(short res) {
byte[] targets = new byte[2];
targets[0] = (byte) (res & 0xff);// ���λ
targets[1] = (byte) ((res >> 8) & 0xff);// �ε�λ
return targets;
}
public static int byte2int(byte[] abytBSComm, int posBin) {
byte[] res = Arrays.copyOfRange(abytBSComm, posBin, abytBSComm.length);
return byte2int(res);
}
public static int byte2int(byte[] res) {
// һ��byte��������24λ���0x??000000��������8λ���0x00??0000
byte[] res0 = Arrays.copyOf(res, 4);
int targets = (res0[0] & 0xff) | ((res0[1] << 8) & 0xff00) // | ��ʾ��λ��
| ((res0[2] << 24) >>> 8) | (res0[3] << 24);
return targets;
}
public static short byte2Short(byte[] res) {
// һ��byte��������24λ���0x??000000��������8λ���0x00??0000
byte[] res0 = Arrays.copyOf(res, 2);
short targets = (short) ((res0[0] & 0xff) | ((res0[1] << 8) & 0xff00));
return targets;
}
public static long ConvertFKTimeToNormalTime(String astrFKTime14)
{
if (astrFKTime14.length() != 14)
return 0;
int year = Integer.parseInt(astrFKTime14.substring(0, 4));
int month = Integer.parseInt(astrFKTime14.substring(4, 6));
int day = Integer.parseInt(astrFKTime14.substring(6, 8));
int hour = Integer.parseInt(astrFKTime14.substring(8, 10));
int minute = Integer.parseInt(astrFKTime14.substring(10, 12));
int second = Integer.parseInt(astrFKTime14.substring(12, 14));
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, hour, minute, second);
return c.getTimeInMillis();
}
public static String GetFKTimeString14(Date date) {
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(date);
}
catch (Exception e)
{
return "19700101010000";
}
}
public static void Mytest(byte[] res,Calendar c) {
c.set(Calendar.YEAR, 1999);
c = Calendar.getInstance();
c.set(Calendar.YEAR, 2001);
res = new byte[]{4,5,6};
}
/* public static String byte2ShortString(byte[] res) {
byte[] res0 = Arrays.copyOf(res, 2);
short targets = (short) ((res0[0] & 0xff) | ((res0[1] << 8) & 0xff00));
String s = Integer.toBinaryString(targets);
return Add0(s, 16);
}
public static String byte2intString(byte[] res) {
byte[] res0 = Arrays.copyOf(res, 4);
int targets = ((res0[0] & 0xff) | ((res0[1] << 8) & 0xff00)
| ((res0[2] << 24) >>> 8) | (res0[3] << 24));
String s = Integer.toBinaryString(targets);
return Add0(s, 32);
}
public static String Add0(String res,int len){
StringBuilder sb = new StringBuilder(res);
while (sb.length()<len) {
sb.insert(0, "0");
}
return sb.toString();
}*/
public static String ConvertFKTimeToNormalTimeString(String astrFKTime14) {
String strRet = "";
if (astrFKTime14.length() != 14)
return strRet;
strRet = astrFKTime14.substring(0, 4) + "-" +
astrFKTime14.substring(4, 6) + "-" +
astrFKTime14.substring(6, 8) + " " +
astrFKTime14.substring(8, 10) + ":" +
astrFKTime14.substring(10, 12) + ":" +
astrFKTime14.substring(12, 14);
return strRet;
}
public static boolean IsNullOrEmptyString(String str) {
if(str == null) return true;
if(str.length() == 0)return true;
return false;
}
public static boolean IsValidTimeString(String astrVal) {
if (IsNullOrEmptyString(astrVal))
return false;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
sdf.parse(astrVal);
return true;
}
catch (Exception e)
{
return false;
}finally {
sdf = null;
}
}
public static String TimeToString(Date date) {
String strRet;
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strRet = sdf.format(date);
return strRet;
}
catch (Exception e)
{
return "1970-1-1 1:0:0";
}
}
}
package com.yl8timer.kqj.yl8timer.tools;
import java.io.Serializable;
import org.springframework.stereotype.Service;
import lombok.Data;
/**
* @author Exrickx
* 前后端交互数据标准
*/
@Service("result")
@Data
public class Result<T> implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 成功标志
*/
private boolean result;
/**
* 失败消息
*/
private String message;
/**
* 返回代码
*/
private String code;
/**
* 时间戳
*/
private long timestamp = System.currentTimeMillis();
/**
* 结果对象
*/
private T data;
/**
* 结果对象
*/
private T other;
/**
* 分页
*/
private Long Current;
/**
* 分页
*/
private Long Pages;
/**
* 分页
*/
private Long Total;
/**
* 分页
*/
private Long Size;
}
package com.yl8timer.kqj.yl8timer.tools;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* @author Exrick
*/
@Service("resultUtil")
public class ResultUtil<T> {
// private static final String CODE_KEY = "code";
// private static final String RESULT_KEY = "result";
// private static final String MESSAGE_KEY = "message";
// private static final String DATA_KEY = "data";
//
// private static final String PAGE_KEY = "page";
// private static final String NUMBER_KEY = "number";
// private static final String SIZE_KEY = "size";
// private static final String TOTALELEMENTS_KEY = "totalelements";
// private static final String TOTALPAGES_KEY = "totalpages";
// private static final String OFFSET_KEY = "offset";
private static final String MESSAGE_SUCCESS = "操作成功";
private static final String MESSAGE_FAIL = "操作失败";
private static final String MESSAGE_UNLOGIN = "会话超时,请重新登录";
// private static final String MESSAGE_ERROR = "操作错误";
// private static final String MESSAGE_KICKOUT = "当前账户已在其他地方登录,请重新登录";
private static final String MESSAGE_PARAMERROR = "参数错误";
// private static final String MESSAGE_UNAUTHORIZED = "授权错误";
// private static final String MESSAGE_UNAUTHENTICATED = "认证错误";
// private static final String MESSAGE_EXCEPTION = "服务器异常";
private static final String STATUS_CODE_SUCCESS = "200";
// private static final String STATUS_CODE_FAIL = "201";
// private static final String STATUS_CODE_ERROR = "202";
private static final String STATUS_CODE_UNLOGIN = "301";
// private static final String STATUS_CODE_KICKOUT = "302";
private static final String STATUS_CODE_UNPARAM = "400";
// private static final String STATUS_CODE_UNAUTHORIZED = "401";
// private static final String STATUS_CODE_UNAUTHENTICATED = "405";
private static final String STATUS_CODE_EXCEPTION = "500";
private Result<T> result;
public ResultUtil() {
result = new Result<>();
result.setResult(true);
result.setMessage("success");
result.setCode(STATUS_CODE_SUCCESS);
}
public Result<T> setData(T t) {
this.result.setData(t);
this.result.setCode(STATUS_CODE_SUCCESS);
return this.result;
}
public Result<T> setSuccessMsg(String msg) {
this.result.setResult(true);
this.result.setMessage(msg);
this.result.setCode(STATUS_CODE_SUCCESS);
this.result.setData(null);
return this.result;
}
public Result<T> setPageData(T t1, Long t2, String msg) {
this.result.setData(t1);
this.result.setTotal(t2);
this.result.setCode(STATUS_CODE_SUCCESS);
this.result.setMessage(msg);
return this.result;
}
public Result<T> setDatas(T t1, T t2, String msg) {
this.result.setData(t1);
this.result.setOther(t2);
this.result.setCode(STATUS_CODE_SUCCESS);
this.result.setMessage(msg);
return this.result;
}
@SuppressWarnings("rawtypes")
public Result<T> setData(T t1, T t2, String msg) {
this.result.setCurrent(((IPage) t1).getCurrent());
this.result.setPages(((IPage) t1).getPages());
this.result.setSize(((IPage) t1).getSize());
this.result.setTotal(((IPage) t1).getTotal());
this.result.setData(t2);
this.result.setCode(STATUS_CODE_SUCCESS);
this.result.setMessage(msg);
return this.result;
}
public Result<T> setData(T t, String msg) {
this.result.setData(t);
this.result.setCode(STATUS_CODE_SUCCESS);
this.result.setMessage(msg);
return this.result;
}
public Result<T> setErrorMsg(T t) {
this.result.setData(t);
this.result.setCode(STATUS_CODE_UNPARAM);
this.result.setMessage(MESSAGE_PARAMERROR);
return this.result;
}
public Result<T> setErrorMsg(String msg) {
this.result.setResult(false);
this.result.setMessage(msg);
this.result.setCode(STATUS_CODE_EXCEPTION);
return this.result;
}
public Result<T> setErrorMsg(String code, String msg) {
this.result.setResult(false);
this.result.setMessage(msg);
this.result.setCode(code);
return this.result;
}
public static <T> Result<T> data(T t) {
return new ResultUtil<T>().setData(t);
}
public static <T> Result<T> data(T t1, T t2, String msg) {
return new ResultUtil<T>().setData(t1, t2, msg);
}
public static <T> Result<T> datas(T t1, T t2, String msg) {
return new ResultUtil<T>().setDatas(t1, t2, msg);
}
public static <T> Result<T> data(T t, String msg) {
return new ResultUtil<T>().setData(t, msg);
}
public static <T> Result<T> pageData(T t, Long t2, String msg) {
return new ResultUtil<T>().setPageData(t, t2, msg);
}
public static <T> Result<T> success() {
return new ResultUtil<T>().setSuccessMsg(MESSAGE_SUCCESS);
}
public static <T> Result<T> success(String msg) {
return new ResultUtil<T>().setSuccessMsg(msg);
}
public static <T> Result<T> error() {
return new ResultUtil<T>().setErrorMsg(MESSAGE_FAIL);
}
public static <T> Result<T> unlogin() {
return new ResultUtil<T>().setErrorMsg(STATUS_CODE_UNLOGIN, MESSAGE_UNLOGIN);
}
public static <T> Result<T> error(String msg) {
return new ResultUtil<T>().setErrorMsg(msg);
}
public static <T> Result<T> error(String code, String msg) {
return new ResultUtil<T>().setErrorMsg(code, msg);
}
public static <T> Result<T> error(T t) {
return new ResultUtil<T>().setErrorMsg(t);
}
}
config.stopBubbling=true
lombok.equalsAndHashCode.callSuper=call
\ No newline at end of file
server:
port: 8095
spring:
datasource:
username: youling8timer
password: (!0YouLing8Timer0!)
url: jdbc:mysql://120.78.162.177:3306/record?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
driver-class-name: com.mysql.cj.jdbc.Driver
jackson:
time-zone: Asia/Shanghai
config:
cleaning-interval: 30 #
timer:
url: http://127.0.0.1:9527/kqdk/punchclock
retry:
#cron: 0 0/30 * * * ?
cron: 0/30 * * * * ? #重试机制
cron2: 0 0/5 * * * ? #定时删除log机制
day: 1 #大于多少天开始删除
ontime:
cron: 0/5 * * * * ? #同步数据扫描时间
overtime: 10 #超时设置任务失败分钟数
environmental-science: dev
\ No newline at end of file
server:
port: 8095
spring:
datasource:
username: youling8timer
password: (!0YouLing8Timer0!)
url: jdbc:mysql://192.168.3.3:33000/record?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
driver-class-name: com.mysql.cj.jdbc.Driver
jackson:
time-zone: Asia/Shanghai
config:
cleaning-interval: 30 #
timer:
#url: http://test-8timer-api.youlingrc.com/kqdk/punchclock
url: http://api.8timer.cn/kqdk/punchclock
retry:
#cron: 0 0/30 * * * ?
cron: 0 0/30 * * * ?
cron2: 0 0 4 * * ? #定时删除log机制
day: 5 #间隔多少天开始删除
ontime:
cron: 0/30 * * * * ? #同步数据扫描时间
overtime: 15 #超时设置任务失败分钟数
environmental-science: pro
\ No newline at end of file
server:
port: 8195
spring:
datasource:
username: youling8timer
password: (!0YouLing8Timer0!)
url: jdbc:mysql://120.78.162.177:3306/record?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
driver-class-name: com.mysql.cj.jdbc.Driver
jackson:
time-zone: Asia/Shanghai
config:
cleaning-interval: 30 #
timer:
url: http://test-8timer-api.youlingrc.com/kqdk/punchclock
retry:
#cron: 0 0/30 * * * ?
cron: 0 0/30 * * * ?
cron2: 0 0 4 * * ? #定时删除log机制
day: 5 #间隔多少天开始删除
ontime:
cron: 0/30 * * * * ? #同步数据扫描时间
overtime: 15 #超时设置任务失败分钟数
environmental-science: test
\ No newline at end of file
spring:
profiles:
active: test
#active: '@environment@'
\ No newline at end of file
package com.yl8timer.kqj.yl8timer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.GetMapping;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
<facet type="web" name="Web">
<configuration>
<webroots />
<sourceRoots>
<root url="file://$MODULE_DIR$/src/main/java" />
<root url="file://$MODULE_DIR$/src/main/resources" />
</sourceRoots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<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" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.apache.tomcat:tomcat-juli:8.5.50" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.11.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.11.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.28" level="project" />
<orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.3.2" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.yaml:snakeyaml:1.23" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.9.9.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.9.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.9.9" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.9" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.9" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.9" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:8.5.50" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:8.5.50" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:8.5.50" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:6.0.17.Final" level="project" />
<orderEntry type="library" name="Maven: javax.validation:validation-api:2.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.3.3.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.4.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: cn.hutool:hutool-all:4.6.1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.springframework.boot:spring-boot-devtools:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.8" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.1.8.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.1.8.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.1.8.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.4.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:5.0.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.11.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:2.23.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.9.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.9.16" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-library:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.1.9.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.1.9.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.6.3" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:8.0.17" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.2.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.1.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.3.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.3.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.3.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.3.0" level="project" />
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.3.0" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:3.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.3" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.3" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid-spring-boot-starter:1.1.10" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.1.10" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.28" level="project" />
</component>
</module>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment