Create Project

This commit is contained in:
yanzg
2018-05-20 21:07:42 +08:00
commit ed711324ae
59 changed files with 5402 additions and 0 deletions

12
.classpath Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_60"/>
<classpathentry kind="lib" path="libs/jackson-annotations-2.2.3.jar"/>
<classpathentry kind="lib" path="libs/jackson-core-2.2.3.jar"/>
<classpathentry kind="lib" path="libs/jackson-databind-2.2.3.jar"/>
<classpathentry kind="lib" path="libs/jna-3.5.2.jar"/>
<classpathentry kind="lib" path="libs/zxing-r12937.jar"/>
<classpathentry kind="lib" path="libs/bcprov-jdk16-139.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

BIN
.project Normal file

Binary file not shown.

View File

@@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

BIN
libs/bcprov-jdk16-139.jar Normal file

Binary file not shown.

Binary file not shown.

BIN
libs/jackson-core-2.2.3.jar Normal file

Binary file not shown.

Binary file not shown.

BIN
libs/jna-3.5.2.jar Normal file

Binary file not shown.

BIN
libs/zxing-r12937.jar Normal file

Binary file not shown.

View File

@@ -0,0 +1,14 @@
package com.light.hard.center;
public class HardCenter {
private static HardServiceInfo m_serviceInfo = null;
public static HardServiceInfo GetInfo() {
if (m_serviceInfo == null) {
m_serviceInfo = new HardServiceInfo();
m_serviceInfo.IsKey = true;
m_serviceInfo.IsCamera = true;
}
return m_serviceInfo;
}
}

View File

@@ -0,0 +1,51 @@
package com.light.hard.center;
import com.light.hard.scan.HardScanBase;
public class HardServiceInfo {
/**
* 是否开启点击摄像机
*/
public boolean IsCamera = false;
/**
* 是否显示按钮
*/
public boolean IsKey = false;
/**
* 是否显示左边自定义按键
*/
public boolean IsKeyLeft = false;
/**
* 是否开启摄像头
*/
public int OpenCameraKey = 0;
/**
* 是否自动开启IC卡
*/
public int OpenICKey = 0;
/**
* 是否自动开启扫描
*/
public int OpenCodeKey = 0;
/**
* 二维码扫描驱动
*/
public HardScanBase ScanCode = null;
/**
* IC卡扫描驱动
*/
public HardScanBase ScanIC = null;
/**
* 照相驱动
*/
public HardScanBase ScanCamera = null;
}

View File

@@ -0,0 +1,166 @@
package com.light.hard.center;
import java.awt.event.KeyEvent;
import java.util.Stack;
import com.light.util.*;
import com.light.hard.scan.*;
/**
* 扫描中心,最主要进行权限的控制和扫描功能的转接
*
* @author Light
*
*/
public class ScanCenter implements DelegateScan {
private HardServiceInfo m_ServiceInfo = null;
private Event<DelegateScan> m_OnRead = new Event<DelegateScan>();
private Stack<Event<DelegateScan>> m_OnReadChche = new Stack<Event<DelegateScan>>();
/**
* 构造函数
*
* @param context
*/
public ScanCenter() {
this.m_ServiceInfo = HardCenter.GetInfo();
this.Init();
}
/**
* 初始化
*/
public void Init() {
if (this.m_ServiceInfo.ScanCode != null) {
this.m_ServiceInfo.ScanCode.getOnRead().Add(this);
if (this.m_ServiceInfo.OpenCodeKey == 0) {
this.m_ServiceInfo.ScanCode.Open();
}
}
if (this.m_ServiceInfo.ScanIC != null) {
this.m_ServiceInfo.ScanIC.getOnRead().Add(this);
if (this.m_ServiceInfo.OpenICKey == 0) {
this.m_ServiceInfo.ScanIC.Open();
}
}
}
public void Close() {
if (this.m_ServiceInfo.ScanCode != null) {
if (this.m_ServiceInfo.OpenCodeKey == 0) {
this.m_ServiceInfo.ScanCode.Close();
}
this.m_ServiceInfo.ScanCode.Dispose();
}
if (this.m_ServiceInfo.ScanIC != null) {
if (this.m_ServiceInfo.OpenICKey == 0) {
this.m_ServiceInfo.ScanIC.Close();
}
this.m_ServiceInfo.ScanIC.Dispose();
}
}
/**
* 当前扫描按钮的事件
*
* @return
*/
public Event<DelegateScan> getOnRead() {
return this.m_OnRead;
}
/**
* 将扫描权限交给到当前对象
*
* @param vScan
* 需要获取到扫描权限的对象
*/
public void PushRead(DelegateScan vScan) {
this.m_OnReadChche.push(this.m_OnRead);
this.m_OnRead = new Event<DelegateScan>();
this.m_OnRead.Add(vScan);
}
/**
* 将扫描对象的权限删除,当该权限是在最顶端的时候,会讲权限交给前一个
*
* @param vScan
*/
public void PopRead(DelegateScan vScan) {
boolean isRemove = this.m_OnRead.Remove(vScan);
if (isRemove) {
while (this.m_OnRead.size() == 0) {
if (this.m_OnReadChche.size() == 0) {
break;
}
this.m_OnRead = this.m_OnReadChche.pop();
}
} else {
for (Event<DelegateScan> vItem : this.m_OnReadChche) {
isRemove = vItem.Remove(vScan);
if (isRemove) {
break;
}
}
}
}
@Override
public void Execute(ScanData vData) throws Exception {
this.m_OnRead.Exeucte(new DelegateScanExecute(vData));
}
/**
* 按键按下时
*
* @param keyCode
* 键盘按键
* @param event
* 事件
* @return
* @throws Exception
*/
public boolean OnKeyDown(int keyCode, KeyEvent event) throws Exception {
int vCount = 0;
boolean ret = false;
if (vCount == 0) {
if (keyCode == this.m_ServiceInfo.OpenCodeKey && this.m_ServiceInfo.ScanCode != null) {
this.m_ServiceInfo.ScanCode.Open();
ret = true;
} else if (keyCode == this.m_ServiceInfo.OpenICKey && this.m_ServiceInfo.ScanIC != null) {
this.m_ServiceInfo.ScanIC.Open();
ret = true;
}
}
return ret;
}
/**
* 当按钮松开时
*
* @param vContext
* 上下文
* @param keyCode
* 键盘按键
* @param event
* 事件
* @return
* @throws Exception
*/
public boolean OnKeyUp(int keyCode, KeyEvent event) throws Exception {
int vCount = 0;
boolean ret = false;
if (vCount == 0) {
if (keyCode == this.m_ServiceInfo.OpenCodeKey && this.m_ServiceInfo.ScanCode != null) {
this.m_ServiceInfo.ScanCode.Close();
ret = true;
} else if (keyCode == this.m_ServiceInfo.OpenICKey && this.m_ServiceInfo.ScanIC != null) {
this.m_ServiceInfo.ScanIC.Close();
ret = true;
}
}
return ret;
}
}

View File

@@ -0,0 +1,13 @@
package com.light.hard.common;
/**
* 当设备常规事件触发时
* @author Light
*
*/
public interface DelegateCommon {
/**
* 常规方法
*/
void Execute();
}

View File

@@ -0,0 +1,20 @@
package com.light.hard.common;
import com.light.util.IEventExecute;
/**
* 常规方法触发执行类
* @author Light
*
*/
public class DelegateCommonExecute implements IEventExecute<DelegateCommon> {
/**
* 执行的函数
*/
@Override
public void Execute(DelegateCommon t) throws Exception {
t.Execute();
}
}

View File

@@ -0,0 +1,14 @@
package com.light.hard.common;
/**
* 调试设备时触发的事件的接口
* @author Light
*
*/
public interface DelegateDebug {
/**
* 执行的方法
* @param paras 事件时候的参数
*/
void Execute(Object ... paras);
}

View File

@@ -0,0 +1,29 @@
package com.light.hard.common;
import com.light.util.IEventExecute;
/**
* 调试时候的事件执行类
* @author Light
*
*/
public class DelegateDebugExecute implements IEventExecute<DelegateDebug> {
private Object[] m_object;
/**
* 构造函数
* @param objects 参数信息
*/
public DelegateDebugExecute( Object... objects) {
m_object = objects;
}
/**
* 事件执行的实现主体
*/
@Override
public void Execute(DelegateDebug t) throws Exception {
t.Execute(m_object);
}
}

View File

@@ -0,0 +1,6 @@
package com.light.hard.common;
public interface DelegateError
{
void Execute(Exception ex);
}

View File

@@ -0,0 +1,28 @@
package com.light.hard.common;
import com.light.util.IEventExecute;
/**
* 异常事件处理类
* @author Light
*
*/
public class DelegateErrorExecute implements IEventExecute<DelegateError> {
private Exception m_exception;
/**
* 构造函数
* @param ex 错误异常信息
*/
public DelegateErrorExecute(Exception ex) {
m_exception = ex;
}
/**
* 执行的主体函数
*/
@Override
public void Execute(DelegateError t) throws Exception {
t.Execute(m_exception);
}
}

View File

@@ -0,0 +1,77 @@
package com.light.hard.common;
import java.util.HashMap;
/**
* @类描述:当前硬件的状态
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称HardStatus
* @创建人Administrator
* @创建时间2016-5-26下午2:04:08
*/
public enum HardStatus {
/**
* 关闭
*/
Close(0),
/**
* 打开,但是还没有连接上
*/
Open(1),
/**
* 已经连接上硬件一般不直接使用用于和Open组合使用
*/
Connection(2),
/**
* 关闭中
*/
Closeing(4),
/**
* 打开连接中
*/
OpenConnection(3),
/**
* 打开关闭中
*/
OpenCloseint(5),
/**
* 已连接,正在关闭(未打开,错误状态)
*/
ConnectionCloseint(6),
/**
* 打开连接,并正在关闭
*/
OpenConnectionCloseint(7);
private int intValue;
private static HashMap<Integer, HardStatus> mappings;
private synchronized static HashMap<Integer, HardStatus> getMappings() {
if (mappings == null) {
mappings = new HashMap<Integer, HardStatus>();
}
return mappings;
}
private HardStatus(int value) {
intValue = value;
HardStatus.getMappings().put(value, this);
}
public int getValue() {
return intValue;
}
public static HardStatus forValue(int value) {
return getMappings().get(value);
}
}

View File

@@ -0,0 +1,11 @@
package com.light.hard.common;
/**
* 摘要:定义一种释放分配的资源的方法。
*/
public interface IDisposable {
/**
* 摘要: 执行与释放或重置非托管资源相关的应用程序定义的任务。
*/
void Dispose();
}

View File

@@ -0,0 +1,86 @@
package com.light.hard.common;
import com.light.util.Event;
/**
* @类描述:当前设备状态事件
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称IHardBase
* @创建人Administrator
* @创建时间2016-5-26下午2:04:39
*/
public interface IHardBase extends IDisposable
{
/**
* 当前连接的状态
*/
HardStatus getStatus();
/**
* 是否已经打开
*/
boolean getIsOpen();
/**
* 是否已经连接上
*/
boolean getIsConnection();
/**
* 是否关闭中
*/
boolean getIsCloseing();
/**
* 是否正在读取中
*/
boolean getIsRun();
/**
* 打开硬件,包含硬件搜索,并且打开硬件连接。
*/
void Open();
/**
* 关闭硬件
*/
void Close();
/**
* 调试时用于获取内部数据的状态事件
*/
Event<DelegateDebug> getOnDebug();
/**
* 当触发异常时,执行该函数
*/
Event<DelegateError> getOnError();
//常规事件
/**
* 当执行ScanOpen时会触发该事件
*/
Event<DelegateCommon> getOnOpen();
/**
* 当硬件连接上的时候会触发该事件
*/
Event<DelegateCommon> getOnConnection();
/**
* 当硬件连接断开时触发该事件
*/
Event<DelegateCommon> getOnDisConnection();
/**
* 当执行ScanClose时确定关闭前会触发该事件
*/
Event<DelegateCommon> getOnClosing();
/**
* 当执行ScanClose时,完全关闭后会触发该事件
*/
Event<DelegateCommon> getClosed();
}

View File

@@ -0,0 +1,70 @@
package com.light.hard.print;
/**
* @类描述:字体类型
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称FontStyle
* @创建人Administrator
* @创建时间2016-5-26下午1:26:51
*/
public enum FontStyle {
Regular(0),
/**
* 黑体
*/
Bold(1),
/**
* 斜体
*/
Italic(2),
/**
* 下划线
*/
Underline (4),
/**
* 加删除线
*/
Strikeout(8);
private int value = 0;
private FontStyle(int value){
this.value = value;
}
public static FontStyle ofValue(int value){
switch (value) {
case 0:
return Regular;
case 1:
return Bold;
case 2:
return Italic;
case 4:
return Underline;
case 8:
return Strikeout;
default:
return null;
}
}
public int value(){
return this.value;
}
}

View File

@@ -0,0 +1,89 @@
package com.light.hard.scan;
import java.util.HashMap;
/**
* @类描述: 条码类型
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称CodeType
* @创建人Administrator
* @创建时间2016-5-26下午1:25:35
*/
public enum CodeType {
None(0),
/**
* 条形码
*/
Code(0x0001),
/**
* 二维码
*/
QrCode(0x0002),
/**
* 所有的条码
*/
AllCode(0x0001 | 0x0002),
/**
* IC卡
*/
ICCard(0x0004),
/**
* ID卡、身份证
*/
IDCard(0x0008),
/**
* 所有卡
*/
AllCard(0x0004 | 0x0008),
/**
* 指纹扫描
*/
Finger(0x0010),
/**
* 磁卡
*/
CiKa(0x0020),
/**
* 手机号
*/
Mobile(0x0080),
/**
* 所有
*/
All(0x003F);
private int intValue;
private static HashMap<Integer, CodeType> mappings;
private synchronized static HashMap<Integer, CodeType> getMappings() {
if (mappings == null) {
mappings = new HashMap<Integer, CodeType>();
}
return mappings;
}
private CodeType(int value) {
intValue = value;
CodeType.getMappings().put(value, this);
}
public int getValue() {
return intValue;
}
public static CodeType forValue(int value) {
return getMappings().get(value);
}
}

View File

@@ -0,0 +1,20 @@
package com.light.hard.scan;
/**
* 扫描触发时的接口
*
* @author Light
*
*/
public interface DelegateScan {
/**
* 当扫描触发时的执行方法
*
* @param vData
* 扫描到的数据
* @throws Exception
* 异常信息
*/
void Execute(ScanData vData) throws Exception;
}

View File

@@ -0,0 +1,31 @@
package com.light.hard.scan;
import com.light.util.IEventExecute;
/**
* 扫描的执行类
* @author Light
*
*/
public class DelegateScanExecute implements IEventExecute<DelegateScan>
{
private ScanData m_data;
/**
* 构造函数
* @param data
*/
public DelegateScanExecute(ScanData data)
{
m_data = data;
}
/**
* 执行处理
*/
@Override
public void Execute(DelegateScan t) throws Exception
{
t.Execute(m_data);
}
}

View File

@@ -0,0 +1,570 @@
package com.light.hard.scan;
import java.util.Date;
import java.util.HashMap;
import com.light.util.*;
import com.light.hard.common.*;
/**
* @类描述IC卡设备基本操作类
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称HardScanBase
* @创建人Administrator
* @创建时间2016-5-26下午1:55:19
*/
public abstract class HardScanBase implements IHardScan {
protected static HashMap<Class<?>, Integer> m_OpenCount = new HashMap<Class<?>, Integer>();
protected static Object m_Lock = new Object();
protected HardStatus Status = HardStatus.Close;
protected CodeType ReadType = CodeType.All;
protected int ErrorTimeout;
protected int SuccuessTimeout;
protected boolean AutoConnection;
protected int AutoConnectionTimeout;
private Thread m_Thread = null;
protected boolean m_IsThread = false;
public HardScanBase() {
this.SetStatus(HardStatus.Close);
this.ReadType = CodeType.All;
this.m_IsThread = this.GetIsThread();
this.ErrorTimeout = 500;
this.SuccuessTimeout = 1000;
this.AutoConnectionTimeout = 1000;
this.AutoConnection = false;
}
@Override
public HardStatus getStatus() {
return Status;
}
protected void SetStatus(HardStatus vStatus) {
synchronized (this) {
this.Status = vStatus;
}
}
@Override
public CodeType getReadType() {
return ReadType;
}
@Override
public void setReadType(CodeType value) {
ReadType = value;
}
@Override
public boolean getIsOpen() {
return (this.Status.getValue() & HardStatus.Open.getValue()) > 0;
}
@Override
public boolean getIsConnection() {
return (this.Status.getValue() & HardStatus.Connection.getValue()) > 0;
}
@Override
public boolean getIsCloseing() {
return (this.Status.getValue() & HardStatus.Closeing.getValue()) > 0;
}
@Override
public boolean getIsRun() {
synchronized (this) {
boolean isConn = this.getIsConnection();
boolean isCloseing = this.getIsCloseing();
return isConn && !isCloseing;
}
}
/**
* 扫描失败等待下一次扫描的时间
*/
protected int getErrorTimeout() {
return ErrorTimeout;
}
protected void setErrorTimeout(int value) {
ErrorTimeout = value;
}
/**
* 扫描成功等待下一次扫描的时间
*/
protected int getSuccuessTimeout() {
return SuccuessTimeout;
}
protected void setSuccuessTimeout(int value) {
SuccuessTimeout = value;
}
/**
* 自动连接硬件
*/
public boolean getAutoConnection() {
return AutoConnection;
}
public void setAutoConnection(boolean value) {
AutoConnection = value;
}
/**
* 自动重连硬件的时间
*/
protected int getAutoConnectionTimeout() {
return AutoConnectionTimeout;
}
protected void setAutoConnectionTimeout(int value) {
AutoConnectionTimeout = value;
}
/**
* 调试时用于获取内部数据的状态事件
*/
protected Event<DelegateDebug> OnDebug = new Event<DelegateDebug>();
/**
* 当触发异常时,执行该函数
*/
protected Event<DelegateError> OnError = new Event<DelegateError>();
// 常规事件
/**
* 当执行ScanOpen时会触发该事件
*/
protected Event<DelegateCommon> OnOpen = new Event<DelegateCommon>();
/**
* 当硬件连接上的时候会触发该事件
*/
protected Event<DelegateCommon> OnConnection = new Event<DelegateCommon>();
/**
* 当硬件连接断开时触发该事件
*/
protected Event<DelegateCommon> OnDisConnection = new Event<DelegateCommon>();
/**
* 当执行ScanClose时确定关闭前会触发该事件
*/
protected Event<DelegateCommon> OnClosing = new Event<DelegateCommon>();
/**
* 当执行ScanClose时,完全关闭后会触发该事件
*/
protected Event<DelegateCommon> OnClosed = new Event<DelegateCommon>();
/**
* 当扫描到数据的时候会触发该事件
*/
protected Event<DelegateScan> OnRead = new Event<DelegateScan>();
@Override
public Event<DelegateDebug> getOnDebug() {
return OnDebug;
}
@Override
public Event<DelegateError> getOnError() {
return OnError;
}
@Override
public Event<DelegateCommon> getOnOpen() {
return OnOpen;
}
@Override
public Event<DelegateCommon> getOnConnection() {
return OnConnection;
}
@Override
public Event<DelegateCommon> getOnDisConnection() {
return OnDisConnection;
}
@Override
public Event<DelegateCommon> getOnClosing() {
return OnClosing;
}
@Override
public Event<DelegateCommon> getClosed() {
return OnClosed;
}
@Override
public Event<DelegateScan> getOnRead() {
return OnRead;
}
protected final void TriggerOnConnection() {
this.ExecuteEvent(this.OnConnection);
}
protected final void TriggerOnDisConnection() {
this.ExecuteEvent(this.OnDisConnection);
}
protected final void TriggerOnDebug(Object... arrs) {
this.ExecuteDebug(this.OnDebug, arrs);
}
protected final void TriggerOnError(Exception ex) {
this.ExecuteEvent(this.OnError, ex);
}
protected final boolean TriggerOnRead(ScanData vData) throws InterruptedException {
return this.ExecuteEvent(this.OnRead, vData);
}
/**
* @描述: 事件处理
* @方法名: ExecuteEvent
* @param common
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-26下午1:59:10
* @修改人 Administrator
* @修改时间 2016-5-26下午1:59:10
*/
private void ExecuteEvent(Event<DelegateCommon> common) {
try {
common.Exeucte(new DelegateCommonExecute());
} catch (Exception ex) {
this.ExecuteEvent(this.OnError, ex);
this.ExecuteDebug(this.OnDebug, ex.getMessage());
}
}
/**
* @描述: 异常处理
* @方法名: ExecuteEvent
* @param common
* @param ex
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-26下午2:00:00
* @修改人 Administrator
* @修改时间 2016-5-26下午2:00:00
*/
private void ExecuteEvent(Event<DelegateError> common, Exception ex) {
try {
if (ex != null) {
common.Exeucte(new DelegateErrorExecute(ex));
}
} catch (Exception ex1) {
LogHelper.WriteLog(ex1);
}
}
private void ExecuteDebug(Event<DelegateDebug> debug, Object... paras) {
try {
debug.Exeucte(new DelegateDebugExecute(paras));
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
private Date m_ReadDate = new Date();
/**
* @描述: 扫描到数据后触发的事件
* @方法名: ExecuteEvent
* @param common
* @param data
* @return
* @throws InterruptedException
* @返回类型 boolean
* @创建人 Administrator
* @创建时间 2016-5-26下午2:00:36
* @修改人 Administrator
* @修改时间 2016-5-26下午2:00:36
*/
private boolean ExecuteEvent(final Event<DelegateScan> common, final ScanData data) throws InterruptedException {
if (!this.getIsRun()) {
return false;
}
if (data != null && common != null) {
ThreadHelper.RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
HardScanBase that = HardScanBase.this;
try {
that.m_ReadDate = new Date();
common.Exeucte(new DelegateScanExecute(data));
} catch (Exception ex) {
that.ExecuteEvent(that.OnError, ex);
that.ExecuteDebug(that.OnDebug, ex.getMessage());
}
}
});
}
return true;
}
protected final boolean Sleep(int vMillSecond) throws InterruptedException {
if (vMillSecond == 0) {
return true;
}
LogDate dc = new LogDate();
dc.Clear();
do {
ThreadHelper.sleep(5);
if (!this.getIsRun()) {
return false;
}
dc.Commit();
} while (dc.TotalSecond < vMillSecond);
return true;
}
@Override
public void Dispose() {
this.Close();
}
@Override
public void Open() {
synchronized (this) {
if (!this.getIsOpen()) {
this.SetStatus(HardStatus.Open);
this.ExecuteEvent(this.OnOpen);
if (this.m_IsThread) {
if (this.m_Thread == null) {
this.m_Thread = ThreadHelper.RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
HardScanBase.this.ScanStart();
}
});
}
} else {
this.OpenPort();
if (!this.getIsConnection()) {
this.OpenAutoConnnection();
}
}
}
}
}
/**
* @描述: 打开设备
* @方法名: OpenPort
* @创建人Administrator
* @创建时间2016-5-26下午1:56:33
* @修改人Administrator
* @修改时间2016-5-26下午1:56:33
* @修改备注:
*/
protected boolean OpenPort() {
boolean isOpenHard = false;
if (this.getIsOpen() && !this.getIsConnection()) {
synchronized (m_Lock) {
try {
if (this.HandleLock(1)) {
isOpenHard = this.OpenHard();
}
} catch (Exception ex) {
this.TriggerOnError(ex);
} finally {
if (!isOpenHard) {
this.HandleLock(-1);
}
}
}
if (isOpenHard) {
this.SetStatus(HardStatus.forValue(this.Status.getValue() | HardStatus.Connection.getValue()));
this.TriggerOnConnection();
}
}
return isOpenHard;
}
/**
* @描述: 设备重连
* @方法名: OpenAutoConnnection
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-26下午1:57:16
* @修改人 Administrator
* @修改时间 2016-5-26下午1:57:16
*/
protected void OpenAutoConnnection() {
ThreadHelper.RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
HardScanBase.this.Reconnection();
}
});
}
/**
* 重新连接设备,直接打开或者关闭设备
*
* @throws InterruptedException
*/
private void Reconnection() throws InterruptedException {
do {
this.OpenPort();
if (this.getIsConnection() || !this.AutoConnection) {
break;
}
this.Sleep(this.AutoConnectionTimeout);
} while (this.getIsOpen() && !this.getIsCloseing());
}
/**
* 开始扫描
*
* @throws InterruptedException
*/
protected void ScanStart() throws InterruptedException {
this.Reconnection();
while (this.getIsRun()) {
try {
ScanData vData = this.ReadData();
boolean isRead = this.TriggerOnRead(vData);
if (!isRead) {
break;
}
} catch (Exception ex) {
this.TriggerOnError(ex);
}
}
this.CloseExecute();
this.m_Thread = null;
}
/**
* 关闭设备
*/
protected void CloseExecute() {
try {
this.ClosePort();
if (this.Status != HardStatus.Close) {
this.SetStatus(HardStatus.Close);
this.ExecuteEvent(this.OnClosed);
}
} catch (Exception ex) {
this.TriggerOnError(ex);
}
}
/**
* @描述: 关闭设备端口
* @方法名: ClosePort
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-26下午1:58:01
* @修改人 Administrator
* @修改时间 2016-5-26下午1:58:01
*/
protected void ClosePort() {
if (this.getIsConnection()) {
this.SetStatus(HardStatus.forValue(this.Status.getValue() & (~HardStatus.Connection.getValue())));
synchronized (m_Lock) {
this.HandleLock(-1);
try {
this.CloseHard();
} catch (Exception ex) {
this.TriggerOnError(ex);
}
}
this.TriggerOnDisConnection();
}
}
private Class<?> m_Type = null;
/**
* 触发设备锁
*
* @param vNum
* @return
*/
private boolean HandleLock(int vNum) {
boolean vFlag = false;
if (this.m_Type == null) {
this.m_Type = this.getClass();
}
if (!m_OpenCount.containsKey(this.m_Type)) {
m_OpenCount.put(this.m_Type, 0);
}
if (vNum < 0) {
if (m_OpenCount.get(this.m_Type) + vNum >= 0) {
vFlag = true;
}
} else {
if (m_OpenCount.get(this.m_Type) == 0) {
vFlag = true;
}
}
m_OpenCount.put(this.m_Type, Math.max(0, m_OpenCount.get(this.m_Type) + vNum));
return vFlag;
}
@Override
public void Close() {
synchronized (this) {
this.ExecuteEvent(this.OnClosing);
if (this.getIsOpen()) {
this.SetStatus(HardStatus.forValue((this.Status.getValue() | HardStatus.Closeing.getValue())));
if (!this.m_IsThread) {
this.CloseExecute();
}
}
}
}
/**
* 是否通过线程启动
*
* @return
*/
protected abstract boolean GetIsThread();
/**
* 打开硬件
*
* @throws Exception
*/
protected abstract boolean OpenHard() throws Exception;
/**
* 关闭硬件
*/
protected abstract boolean CloseHard() throws Exception;
/**
* 读取数据
*
* @return 读取到数据
*/
protected abstract ScanData ReadData() throws Exception;
}

View File

@@ -0,0 +1,39 @@
package com.light.hard.scan;
import com.light.hard.common.IHardBase;
import com.light.util.Event;
/**
* 扫描的实现接口
*
* @author Light
*
*/
public interface IHardScan extends IHardBase {
/**
* 打开之后自动连接
*/
boolean getAutoConnection();
/**
* 设置自动连接时间
*/
void setAutoConnection(boolean value);
/**
* 码类型
*/
CodeType getReadType();
/**
* 设置扫描类型,必须得支持
*
* @param value
*/
void setReadType(CodeType value);
/**
* 当扫描到数据的时候会触发该事件
*/
Event<DelegateScan> getOnRead();
}

View File

@@ -0,0 +1,28 @@
package com.light.hard.scan;
/**
* 扫描数据并写入数据的接口
* @author Light
*
*/
public interface IHardScanWrite extends IHardScan
{
/**
是否允许写入数据
*/
boolean getIsWrite();
/**
写入数据
@param vData 需要写入的数据
*/
boolean Write(String vData);
/**
停止写入
@return 是否停止成功
*/
boolean StopWrite();
}

View File

@@ -0,0 +1,42 @@
package com.light.hard.scan;
/**
* @类描述: 扫描到的信息,如二维码、条码、IC卡卡号、身份证、磁卡
* @项目名称ScanDemo
* @包名: piaost.client.hard
* @类名称ScanData
* @创建人Administrator
* @创建时间2016-5-26下午2:15:08
*/
public class ScanData
{
/**
是否已经处理
*/
public boolean IsHandle;
/**
数据类型
*/
public CodeType ReadType;
/**
卡号
*/
public String Content;
/**
* 图片信息
*/
public Object Bitmap;
/**
扩展信息,如身份证的的其他信息
*/
public Object Extend;
}

View File

@@ -0,0 +1,435 @@
package com.light.util;
/**
* 通信格式转换
*
* Java和一些windows编程语言如c、c++、delphi所写的网络程序进行通讯时需要进行相应的转换 高、低字节之间的转换
* windows的字节序为低字节开头 linux,unix的字节序为高字节开头 java则无论平台变化都是高字节开头
*/
public class ByteConvertHelper {
public static byte[] toLH(long n, int max) {
byte[] b = new byte[max];
for (int i = 0; i < max; i++) {
int offset = i * 8;
b[i] = (byte) (n >> offset & 0xff);
}
return b;
}
public static byte[] toHH(long n, int max) {
byte[] b = new byte[max];
for (int i = 0; i < max; i++) {
int offset = (max - 1 - i) * 8;
b[i] = (byte) (n >> offset & 0xff);
}
return b;
}
public static byte[] toLH(long n) {
return toLH(n, 8);
}
public static byte[] toHH(long n) {
return toHH(n, 8);
}
/**
* 将int转为低字节在前高字节在后的byte数组
*
* @param n
* int
* @return byte[]
*/
public static byte[] toLH(int n) {
return toLH(n, 4);
}
/**
* 将int转为高字节在前低字节在后的byte数组
*
* @param n
* int
* @return byte[]
*/
public static byte[] toHH(int n) {
return toHH(n, 4);
}
/**
* 将short转为低字节在前高字节在后的byte数组
*
* @param n
* short
* @return byte[]
*/
public static byte[] toLH(short n) {
return toLH(n, 2);
}
/**
* 将short转为高字节在前低字节在后的byte数组
*
* @param n
* short
* @return byte[]
*/
public static byte[] toHH(short n) {
return toHH(n, 2);
}
/**
* 将float转为低字节在前高字节在后的byte数组
*/
public static byte[] toLH(float f) {
return toLH(Float.floatToRawIntBits(f));
}
/**
* 将float转为高字节在前低字节在后的byte数组
*/
public static byte[] toHH(float f) {
return toHH(Float.floatToRawIntBits(f));
}
/**
* 将低字节转换为长整形
*
* @param bytes
* 字节
* @param off
* 开始位置
* @param max
* 最大位置
* @return
*/
public static long lBytesToLong(byte[] bytes, int off, int max) {
long ret = 0;
for (int i = 0; i < max; i++) {
int b = bytes[off + i] & 0xFF;
int offset = i * 8;
ret |= (b << offset);
}
return ret;
}
/**
* 将高字节转换为长整型
*
* @param bytes
* 字节
* @param off
* 开始位置
* @param max
* 最大位置
* @return
*/
public static long hBytesToLong(byte[] bytes, int off, int max) {
long ret = 0;
for (int i = 0; i < max; i++) {
int b = bytes[off + i] & 0xFF;
int offset = (max - 1 - i) * 8;
ret |= (b << offset);
}
return ret;
}
/**
* 将高字节数组转换为long
*
* @param b
* @return
*/
public static long hBytesToLong(byte[] b) {
return hBytesToLong(b, 0);
}
/**
* 将高字节数组转换为long
*
* @param b
* byte[]
* @param offset
* long
* @return long
*/
public static long hBytesToLong(byte[] b, int off) {
return hBytesToLong(b, off, 8);
}
/**
* 将低字节数组转换为long
*
* @param b
* byte[]
* @return long
*/
public static long lBytesToLong(byte[] b) {
return lBytesToLong(b, 0);
}
/**
* 将低字节数组转换为long
*
* @param b
* @param off
* @return
*/
public static long lBytesToLong(byte[] b, int off) {
return lBytesToLong(b, off, 8);
}
/**
* 将高字节数组转换为int
*
* @param b
* @return
*/
public static int hBytesToInt(byte[] b) {
return hBytesToInt(b, 0);
}
/**
* 将高字节数组转换为int
*
* @param b
* byte[]
* @param offset
* int
* @return int
*/
public static int hBytesToInt(byte[] b, int off) {
return (int) hBytesToLong(b, off, 4);
}
/**
* 将低字节数组转换为int
*
* @param b
* byte[]
* @return int
*/
public static int lBytesToInt(byte[] b) {
return lBytesToInt(b, 0);
}
/**
* 将低字节数组转换为int
*
* @param b
* @param off
* @return
*/
public static int lBytesToInt(byte[] b, int off) {
return (int) lBytesToLong(b, off, 4);
}
/**
* 高字节数组到short的转换
*
* @param b
* @param off
* @return
*/
public static short hBytesToShort(byte[] b) {
return hBytesToShort(b, 0);
}
/**
* 高字节数组到short的转换
*
* @param b
* @param off
* @return
*/
public static short hBytesToShort(byte[] b, int off) {
return (short) hBytesToLong(b, off, 2);
}
/**
* 低字节数组到short的转换
*
* @param b
* @param off
* @return
*/
public static short lBytesToShort(byte[] b) {
return lBytesToShort(b, 0);
}
/**
* 低字节数组到short的转换
*
* @param b
* @param off
* @return
*/
public static short lBytesToShort(byte[] b, int off) {
return (short) lBytesToLong(b, off, 2);
}
/**
* 高字节数组转换为float
*
* @param b
* byte[]
* @return float
*/
public static float hBytesToFloat(byte[] b) {
int i = hBytesToInt(b);
return Float.intBitsToFloat(i);
}
/**
* 低字节数组转换为float
*
* @param b
* byte[]
* @return float
*/
public static float lBytesToFloat(byte[] b) {
int i = lBytesToInt(b);
return Float.intBitsToFloat(i);
}
/**
* 将byte数组中的元素倒序排列
*/
public static byte[] bytesReverseOrder(byte[] b) {
int length = b.length;
byte[] result = new byte[length];
for (int i = 0; i < length; i++) {
result[length - i - 1] = b[i];
}
return result;
}
/**
* 将int类型的值转换为字节序颠倒过来对应的int值
*
* @param i
* int
* @return int
*/
public static int reverseInt(int i) {
int result = hBytesToInt(toLH(i));
return result;
}
/**
* 将short类型的值转换为字节序颠倒过来对应的short值
*
* @param s
* short
* @return short
*/
public static short reverseShort(short s) {
short result = hBytesToShort(toLH(s));
return result;
}
public static byte[] GetBytes(short value) {
return toHH(value);
}
public static byte[] GetBytes(int value) {
return toHH(value);
}
public static byte[] GetBytes(long value) {
return toHH(value);
}
/**
* 将float类型的值转换为字节序颠倒过来对应的float值
*
* @param f
* float
* @return float
*/
public static float reverseFloat(float f) {
float result = hBytesToFloat(toLH(f));
return result;
}
public static short HostToNetworkOrder(short vFrom) {
return hBytesToShort(toLH(vFrom));
}
public static int HostToNetworkOrder(int vFrom) {
return hBytesToInt(toLH(vFrom));
}
public static long HostToNetworkOrder(long vFrom) {
return hBytesToLong(toLH(vFrom));
}
public static short NetworkToHostOrder(short vFrom) {
return lBytesToShort(toHH(vFrom));
}
public static int NetworkToHostOrder(int vFrom) {
return lBytesToInt(toHH(vFrom));
}
public static long NetworkToHostOrder(long vFrom) {
return lBytesToLong(toHH(vFrom));
}
/**
* 将String转为byte数组
*/
public static byte[] stringToBytes(String s, int length) {
while (s.getBytes().length < length) {
s += " ";
}
return s.getBytes();
}
/**
* 将字节数组转换为String
*
* @param b
* byte[]
* @return String
*/
public static String bytesToString(byte[] b) {
StringBuffer result = new StringBuffer("");
int length = b.length;
for (int i = 0; i < length; i++) {
result.append((char) (b[i] & 0xff));
}
return result.toString();
}
/**
* 将字符串转换为byte数组
*
* @param s
* String
* @return byte[]
*/
public static byte[] stringToBytes(String s) {
return s.getBytes();
}
/**
* 打印byte数组
*/
public static void printBytes(byte[] bb) {
int length = bb.length;
for (int i = 0; i < length; i++) {
System.out.print(bb + " ");
}
System.out.println("");
}
public static void logBytes(byte[] bb) {
int length = bb.length;
String out = "";
for (int i = 0; i < length; i++) {
out = out + bb + " ";
}
}
}

View File

@@ -0,0 +1,6 @@
package com.light.util;
public interface DelegateCode
{
void Execute() throws Exception;
}

View File

@@ -0,0 +1,10 @@
package com.light.util;
public class DelegateCodeExecute implements IEventExecute<DelegateCode>
{
@Override
public void Execute(DelegateCode t) throws Exception
{
t.Execute();
}
}

View File

@@ -0,0 +1,17 @@
package com.light.util;
import java.util.Date;
/**
* 获取当前时间的接口,有些设备不支持直接获取当前时间,需要调用API接口
*
* @author Light
*
*/
public interface DelegateNow {
/**
* 返回当前时间
* @return
*/
Date Execute();
}

View File

@@ -0,0 +1,5 @@
package com.light.util;
public interface DelegateString {
void Execute(String str) throws Exception;
}

View File

@@ -0,0 +1,5 @@
package com.light.util;
public interface DelegateWriteLog{
void Execute(String vMsg) throws Exception;
}

View File

@@ -0,0 +1,38 @@
package com.light.util;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class DesHelper {
public static String encode(byte[] siv, String data, String skey)
throws Exception {
DESKeySpec keySpec = new DESKeySpec(skey.getBytes());// 设置密钥参数
AlgorithmParameterSpec iv = new IvParameterSpec(siv);// 设置向量 , 加密算法的参数接口IvParameterSpec是它的一个实现
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
return Base64.encode(pasByte);
}
public static String decode(byte[] siv, String data, String skey)
throws Exception {
DESKeySpec keySpec = new DESKeySpec(skey.getBytes());// 设置密钥参数
AlgorithmParameterSpec iv = new IvParameterSpec(siv);// 设置向量, 加密算法的参数接口IvParameterSpec是它的一个实现
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] pasByte = deCipher.doFinal(Base64.decode(data));
return new String(pasByte, "UTF-8");
}
}

View File

@@ -0,0 +1,40 @@
package com.light.util;
import java.util.*;
import com.fasterxml.jackson.databind.node.*;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class DictionaryHelper {
/**
* @描述: 将对象转map
* @方法名: ConvertDictionary
* @param item
* @return
* @返回类型 HashMap
* @创建人 Administrator
* @创建时间 2016-5-25下午6:41:36
* @修改人 Administrator
* @修改时间 2016-5-25下午6:41:36
*/
public static HashMap ConvertDictionary(Object item) {
HashMap data = null;
if (item instanceof HashMap) {
data = (HashMap) item;
} else if (data == null && item instanceof ObjectNode) {
data = new HashMap<String, Object>();
ObjectNode jObject = (ObjectNode) item;
Iterator<String> keys = jObject.fieldNames();
while (keys.hasNext()) {
String fieldName = keys.next();
data.put(fieldName, jObject.get(fieldName).textValue());
}
} else if (data == null) {
data = new HashMap<String, Object>();
}
return data;
}
}

View File

@@ -0,0 +1,72 @@
package com.light.util;
import java.lang.reflect.Method;
import java.util.HashMap;
public class EnumHelper {
public static <T extends Enum<T>> T ConvertEnum(String vStr, T vDefault) {
Class<T> vType = (Class<T>) vDefault.getClass();
T result = vDefault;
try {
if (!StringHelper.IsEmpty(vStr)) {
result = Enum.valueOf(vType, vStr);
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, vStr);
}
return result;
}
public static <T> T ConvertEnum(Class<T> vType, String vStr) {
return ConvertEnum(vType, vStr, null);
}
@SuppressWarnings("unchecked")
public static <T> T ConvertEnum(Class<T> vType, String vStr, T vDefault) {
T result = vDefault;
try {
if (StringHelper.isInteger(vStr)) {
result = ConvertEnum(vType, StringHelper.GetInt(vStr));
} else if (!StringHelper.IsEmpty(vStr)) {
result = (T) Enum.valueOf((Class) vType, vStr);
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, vStr);
}
if (result == null && vDefault == null) {
result = ConvertEnum(vType, 0);
}
return result;
}
private static HashMap<Class, Method> CacheMethod = new HashMap<Class, Method>();
public static <T> T ConvertEnum(Class<T> vType, int i) {
T result = null;
try {
if (CacheMethod.containsKey(vType)) {
Method met = CacheMethod.get(vType);
result = (T) met.invoke(null, i);
} else {
Method[] vMets = vType.getMethods();
for (Method vMet : vMets) {
String vName = vMet.getName();
if (vName.equals("forValue")
&& vMet.getParameterTypes().length == 1) {
Class vTempType = vMet.getParameterTypes()[0];
Object obj = vMet.invoke(null, i);
result = (T) obj;
CacheMethod.put(vType, vMet);
break;
}
}
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, "0");
}
return result;
}
}

View File

@@ -0,0 +1,59 @@
package com.light.util;
import java.util.*;
/**
* @绫绘弿杩帮細浜嬩欢瀵硅薄闆嗕腑澶勭悊浠ュ強浜嬩欢鐨勭Щ闄や笌娣诲姞
* @椤圭洰鍚嶇О锛歋canDemo
* @鍖呭悕锛<E68295> piaost.base
* @绫诲悕绉帮細Event
* @鍒涘缓浜猴細Administrator
* @鍒涘缓鏃堕棿锛<E6A3BF>2016-5-25涓嬪崍4:18:02
*/
public class Event<T>
{
private List<T> m_List = new ArrayList<T>();
public void Add(T t)
{
if (t != null)
{
m_List.add(t);
}
}
public <M extends IEventExecute<T>> void Exeucte(M m) throws Exception
{
for (T item : m_List)
{
m.Execute(item);
}
}
public boolean Remove(T t)
{
if (t != null)
{
return m_List.remove(t);
}
return false;
}
public void Clear()
{
m_List.clear();
}
public boolean Contants(T t)
{
if (t != null)
{
return m_List.contains(t);
}
return false;
}
public int size()
{
return m_List.size();
}
}

View File

@@ -0,0 +1,307 @@
package com.light.util;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class FileHelper {
static {
try {
m_BasePath = getApplicatoinPath();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String m_BasePath;
public static String GetBasePath() {
return m_BasePath;
}
public static void SetBasePath(String path) {
m_BasePath = path;
}
public static File[] getFiles(String path) {
File root = new File(path);
if (root.exists()) {
return root.listFiles();
}
return null;
}
/**
* 文件删除
*
* @param day1
* @param day3
* @param size
* @param path
* @throws Exception
*/
public static void deleteFile(long day1, long day3, long size, String path) throws Exception {
File[] files = getFiles(path);
if (files == null) {
return;
}
for (File file : files) {
if (file.isDirectory()) {
continue;
}
if (System.currentTimeMillis() - new SimpleDateFormat("yyyyMMdd").parse(file.getName().replaceAll("[.][^.]*$", "")).getTime() > day3) {
file.delete();
continue;
}
if (file.length() > size) {
file.delete();
continue;
}
}
}
/**
* 递归删除文件和文件夹
*
* @param file
* 要删除的根目录
*/
public static void deleteFile(File file) {
if (!file.exists()) {
return;
} else {
if (file.isFile()) {
if (System.currentTimeMillis() - file.lastModified() > 2 * 24 * 60 * 60 * 1000) {
file.delete();
}
return;
}
if (file.isDirectory()) {
File[] childFile = file.listFiles();
if (childFile == null || childFile.length == 0) {
file.delete();
return;
}
for (File f : childFile) {
deleteFile(f);
}
}
}
}
public static String combine(String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
public static String getUrl(String url) throws Exception {
if (url.startsWith("~")) {
url = StringHelper.trimStart(url, '\\', '/', '~');
try {
url = getApplicatoinPath() + "//" + url;
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
url = url.replace('\\', '/');
if (url.indexOf(":") == -1) {
url = combine(getApplicatoinPath(), url);
}
return url;
}
public static String getUrl(String url, String defUrl) throws Exception {
if (StringHelper.IsEmpty(url)) {
url = defUrl;
}
return getUrl(url);
}
// / <summary>
// / 程序运行起始路径
// / </summary>
public static String getApplicatoinPath() throws Exception {
File directory = new File(".");
String vPath = directory.getCanonicalPath();
return vPath;
}
public static void Write(String vPath, String vName, HashMap<String, Object> vDic) throws Exception {
if (StringHelper.IsEmpty(vName)) {
vName = String.format(" {0:yyyy-MM-dd HH-mm-ss-ffff}.js", new Date());
}
String filePath = FileHelper.GetFilePath(vPath, vName);
String vJson = JSONHelper.SerializeObject(vDic);
WriteText(filePath, vJson);
}
public static HashMap<String, Object> Read(String vPath, String vName) throws Exception {
String filePath = FileHelper.GetFilePath(vPath, vName);
String json = ReadText(filePath);
HashMap<String, Object> result = null;
try {
result = JSONHelper.DeserializeObject(json, HashMap.class);
} catch (Exception ex) {
ex.printStackTrace();
LogHelper.WriteLog(ex);
throw new Exception("文件" + filePath + "格式不正确!");
}
return result;
}
public static String[] ReadList(String vPath) {
File file = new File(vPath);
if (file.exists()) {
return new String[0];
}
List<String> list = new ArrayList<String>();
File[] array = file.listFiles();
for (int i = 0; i < array.length; i++) {
File fileInfo = array[i];
list.add(fileInfo.getName());
}
return (String[]) list.toArray();
}
public static void Clear(String vPath) {
String[] array = FileHelper.ReadList(vPath);
String[] array2 = array;
for (int i = 0; i < array2.length; i++) {
String vName = array2[i];
Delete(vPath, vName);
}
}
public static void Delete(String vPath, String vName) {
String filePath = FileHelper.GetFilePath(vPath, vName);
Delete(filePath);
}
public static void Delete(String path) {
try {
File file = new File(path);
if (file.exists()) {
file.delete();
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
public static String GetFilePath(String vPath, String vName) {
vPath = vPath.replace("/", "\\");
if (!vPath.endsWith("\\")) {
vPath += "\\";
}
return vPath + vName;
}
public static String GetPath(String vFrontPath, String vPath) {
String separator = "[\\/\\\\]";
String[] array = vFrontPath.split(separator);
String[] array2 = vPath.split(separator);
List<String> list = new ArrayList<String>();
String[] array3 = array;
for (int i = 0; i < array3.length; i++) {
String vStr = array3[i];
FileHelper.HandlePath(list, vStr);
}
if (!vFrontPath.endsWith("/") && !vFrontPath.endsWith("\\")) {
list.remove(list.size() - 1);
}
String[] array4 = array2;
for (int j = 0; j < array4.length; j++) {
String vStr2 = array4[j];
FileHelper.HandlePath(list, vStr2);
}
String[] vStrs = (String[]) list.toArray();
return StringHelper.join("/", vStrs);
}
private static void HandlePath(List<String> vList, String vStr) {
String text = vStr.trim();
if (text == ".") {
return;
}
if (text == "..") {
vList.remove(vList.size() - 1);
return;
}
vList.add(text);
}
public static String ReadText(String path) throws Exception {
File file = new File(path);
if (!file.exists()) {
return "";
}
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));// 构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) { // 使用readLine方法一次读一行
// sb.append("\n");
sb.append(s);
}
} finally {
if (br != null) {
br.close();
br = null;
}
}
return sb.toString();
}
public static void WriteText(String path, String vText) throws Exception {
File file = new File(path);
if (!file.exists()) {
File f = file.getParentFile();
if (f.mkdir() || f.mkdirs()) {
file.createNewFile();
} else
file.createNewFile();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path, false);
fos.write(vText.getBytes("utf-8"));
} finally {
if (fos != null) {
fos.close();
fos = null;
}
}
}
public static boolean IsFileInUse(String fileName) {
boolean inUse = true;
FileInputStream fs = null;
try {
try {
fs = new FileInputStream(fileName);
inUse = false;
} catch (Exception ex) {
inUse = true;
}
} finally {
if (fs != null)
try {
fs.close();
} catch (IOException e) {
LogHelper.WriteLog(e);
}
}
return inUse;
}
public static boolean Exists(String vPath) {
File vFile = new File(vPath);
return vFile.exists();
}
}

View File

@@ -0,0 +1,16 @@
package com.light.util;
/**
* 执行的时候得事件处理类
* @author Light
*
* @param <T> 接口
*/
public interface IEventExecute<T> {
/**
* 事件的执行主体
* @param t 接口
* @throws Exception 异常错误
*/
void Execute(T t) throws Exception;
}

View File

@@ -0,0 +1,47 @@
package com.light.util;
import com.fasterxml.jackson.databind.*;
public class JSONHelper
{
private static ObjectMapper mapper = new ObjectMapper();
static
{
mapper.setPropertyNamingStrategy(new MyNameStrategy());
}
/**
* 获取泛型的Collection Type
*
* @param collectionClass
* 泛型的Collection
* @param elementClasses
* 元素类
* @return JavaType Java类型
* @since 1.0
*/
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses)
{
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
public static <T> T DeserializeObject(String value, Class<T> type) throws Exception
{
return mapper.readValue(value, type);
}
public static <T> T DeserializeObject(String vJson, JavaType type) throws Exception
{
return (T) mapper.readValue(vJson, type);
}
public static String SerializeObject(Object value) throws Exception
{
return mapper.writeValueAsString(value);
}
public static String SerializeObject(Object value, boolean isLine) throws Exception
{
return mapper.writeValueAsString(value);
}
}

View File

@@ -0,0 +1,115 @@
package com.light.util;
import java.util.Date;
/**
* 日志追踪器
*
* @author Light
*/
public class LogDate {
public static DelegateNow GetNow = null;
public static int MinMillSecond = 1;
static {
GetNow = new DelegateNow() {
@Override
public Date Execute() {
return new Date();
}
};
}
public LogDate() {
this("");
}
public LogDate(String vTitle) {
this.Clear();
if (!StringHelper.IsEmpty(vTitle)) {
this.Begin(vTitle);
}
}
public StringBuilder Log = null;
private Date Start = new Date();
private Date End = new Date();
public double LastSecond = 0;
public double TotalSecond = 0;
public int Level = 1;
public int getLevel() {
return Level;
}
public void setLevel(int level) {
Level = level;
}
public StringBuilder getLog() {
return Log;
}
public Date getStart() {
return Start;
}
public Date getEnd() {
return End;
}
public double getLastSecond() {
return LastSecond;
}
public double getTotalSecond() {
return TotalSecond;
}
public void Begin() {
this.Start = GetNow.Execute();
}
public void Begin(String vTitle) {
this.Begin();
this.Log.append(vTitle);
}
public void Commit() {
this.End = GetNow.Execute();
double vTotal = this.End.getTime() - this.Start.getTime();
this.LastSecond = vTotal - this.TotalSecond;
this.TotalSecond = vTotal;
}
public void Commit(String vTag, Object... args) {
this.Commit();
if (!StringHelper.isNullOrEmpty(vTag)) {
String vLog = String.format("\r\n%s: %f ms 总共: %f ms ", String.format(vTag, args), this.LastSecond, this.TotalSecond);
this.Log.append(vLog);
}
}
public void Clear() {
this.Start = GetNow.Execute();
this.End = GetNow.Execute();
this.LastSecond = 0;
this.TotalSecond = 0;
this.Log = new StringBuilder();
}
public void WriteLog() {
// 执行时间为0的不显示日志
if (this.TotalSecond >= MinMillSecond) {
String vLog = this.Log.toString();
if (!StringHelper.IsEmpty(vLog)) {
if (this.Level > 0) {
this.Level = LogHelper.LogLevel.Big.getValue();
}
LogHelper.WriteLog(this.Start, this.Level, vLog);
}
this.Clear();
}
}
}

View File

@@ -0,0 +1,275 @@
package com.light.util;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
public class LogHelper {
public enum LogLevel {
None(0), Common(1), BigCommon(2), Exception(3), Big(99);
private int Value;
private static HashMap<Integer, LogLevel> mappings;
private synchronized static HashMap<Integer, LogLevel> getMappings() {
if (mappings == null) {
mappings = new HashMap<Integer, LogLevel>();
}
return mappings;
}
private LogLevel(int value) {
Value = value;
LogLevel.getMappings().put(value, this);
}
public int getValue() {
return Value;
}
public static LogLevel forValue(int value) {
return getMappings().get(value);
}
}
private static DelegateWriteLog OnWriteLog;
public static DelegateWriteLog getOnWriteLog() {
return OnWriteLog;
}
public static void setOnWriteLog(DelegateWriteLog value) {
OnWriteLog = value;
}
private static int Level;
public static int getLevel() {
return Level;
}
public static void setLevel(int value) {
Level = value;
}
private static boolean IsConsole;
public static boolean getIsConsole() {
return IsConsole;
}
public static void setIsConsole(boolean value) {
IsConsole = value;
}
private static boolean IsFile;
public static boolean getIsFile() {
return IsFile;
}
public static void setIsFile(boolean value) {
IsFile = value;
}
private static LinkedList<LogInfo> m_Log = new LinkedList<LogInfo>();
private static class LogInfo {
public Date Now = new Date();
public int Count;
public String Message;
public Exception Exception;
@SuppressWarnings("unused")
public LogInfo(Date dateTime, Exception ex) {
this(dateTime, ex, "");
}
public LogInfo(Date dateTime, String vMsg) {
this(dateTime, null, vMsg);
}
public LogInfo(Date dateTime, Exception ex, String vMsg) {
this.Now = dateTime;
this.Exception = ex;
this.Message = vMsg;
}
}
static {
setLevel(2);
setIsConsole(false);
setIsFile(true);
StartLog();
}
private static void StartLog() {
RunInterval ri = new RunInterval();
ri.setTime(100);
ri.setCode(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
WriteFile();
}
});
ThreadHelper.RunThread(ri);
}
static HashMap<String, LogInfo> m_CacheException = new HashMap<String, LogHelper.LogInfo>();
private static void WriteFile() throws Exception {
LinkedList<LogInfo> vQueue = m_Log;
if (vQueue.size() < 1) {
return;
}
String vPath = FileHelper.GetBasePath() + "/Temp/Log/";
String vUrl = FileHelper.getUrl(vPath, vPath);
/*** 有问题 **/
StreamWriter sw = null;
/*** 有问题 **/
// 当需要将日志写入文件时,打开文件流
if (getIsFile()) {
try {
Date vNow = new Date();
String vFile = String.format("%s/%s.log", vUrl, new SimpleDateFormat("yyyyMMdd").format(vNow));
File file = new File(vFile);
// String vDic = file.getParent();
if (!file.exists()) {
File f = file.getParentFile();
if (f.mkdirs()) {
file.createNewFile();
} else {
file.createNewFile();
}
}
sw = new StreamWriter(vFile, true, "UTF-8");
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
// 循环处理日志
do {
try {
LogInfo vInfo = null;
if (vQueue.isEmpty()) {
break;
}
vInfo = vQueue.poll();
if (vInfo == null) {
continue;
}
if (vInfo.Exception != null) {
if (StringHelper.isNullOrEmpty(vInfo.Message)) {
vInfo.Message = String.format("%s:\r\n%s", vInfo.Exception.getMessage(), vInfo.Exception);
} else {
vInfo.Message = String.format("%s:\r\n%s\r\n异常参数:%s", vInfo.Exception.getMessage(), vInfo.Exception, vInfo.Message);
}
String vkey = StringHelper.md5(vInfo.Message);
LogInfo vHis = m_CacheException.get(vkey);
if (vHis == null) {
m_CacheException.put(vkey, vInfo);
} else {
vHis.Count++;
if ((vInfo.Now.getTime() - vHis.Now.getTime()) < 15 * 60 * 1000) {
continue;
}
vInfo.Message = String.format("(%d次) %s", vHis.Count, vInfo.Message);
vHis.Count = 0;
vHis.Now = vInfo.Now;
}
}
if (StringHelper.isNullOrEmpty(vInfo.Message)) {
continue;
}
final String vResult = String.format("\r\n%s\t%s", new SimpleDateFormat("HH:mm:ss.SSS").format(vInfo.Now), vInfo.Message);
if (sw != null) {
sw.WriteLine(vResult);
}
// 将日志写入控制台
if (getIsConsole() && getOnWriteLog() != null) {
OnWriteLog.Execute(vResult);
}
if (sw != null && vQueue.isEmpty()) {
Thread.sleep(100); // 等待100毫秒防止文件打开关闭消耗资源
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} while (true);
try {
if (sw != null) {
sw.Close();
sw = null;
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static void WriteLog(Exception ex) {
ex.printStackTrace();
WriteLog(ex, "");
}
public static void WriteLog(Exception ex, String vMessage) {
AddEnqueue(LogLevel.Exception.getValue(), new LogInfo(new Date(), ex, vMessage));
}
public static void WriteLog(StackTraceElement... items) {
StringBuffer sb = new StringBuffer();
for (StackTraceElement item : items) {
sb.append(item.toString());
sb.append("\r\n");
}
WriteLog(sb.toString());
}
public static void WriteLog(String vMsg, Object... objs) {
WriteLog(LogLevel.None, vMsg, objs);
}
public static void WriteLog(LogLevel vLevel, String vMsg, Object... objs) {
WriteLog(vLevel.getValue(), vMsg, objs);
}
public static void WriteLog(int vLevel, String vMsg, Object... objs) {
WriteLog(new Date(), vLevel, vMsg, objs);
}
public static void WriteLog(Date vNow, int vLevel, String vMsg, Object... objs) {
if (objs != null && objs.length > 0) {
try {
vMsg = String.format(vMsg, objs);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
AddEnqueue(vLevel, new LogInfo(vNow, vMsg));
}
private static void AddEnqueue(int vLevel, LogInfo vInfo) {
if (vLevel < getLevel()) {
return;
}
m_Log.offer(vInfo);
}
}

View File

@@ -0,0 +1,35 @@
package com.light.util;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
public class MyNameStrategy extends PropertyNamingStrategy {
@Override
public String nameForField(MapperConfig config, AnnotatedField field,
String defaultName) {
String vName = field.getName();
return vName;
}
@Override
public String nameForGetterMethod(MapperConfig config,
AnnotatedMethod method, String defaultName) {
String vName = method.getName();
if (vName.startsWith("get")) {
return vName.substring(3);
}
return vName;
}
@Override
public String nameForSetterMethod(MapperConfig config,
AnnotatedMethod method, String defaultName) {
String vName = method.getName();
if (vName.startsWith("set")) {
return vName.substring(3);
}
return vName;
}
}

View File

@@ -0,0 +1,472 @@
package com.light.util;
import java.math.*;
import java.util.*;
import java.lang.reflect.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
/**
* @类描述:对象操作类
* @项目名称ScanDemo
* @包名: piaost.util
* @类名称ObjectHelper
* @创建人Administrator
* @创建时间2016-5-25下午5:37:06
*/
@SuppressWarnings("rawtypes")
public class ObjectHelper {
/**
* @描述: json输出结果转意输结果不带“”
* @方法名: Get
* @param obj
* json对象
* @return
* @返回类型 Object
* @创建人 Administrator
* @创建时间 2016-5-25下午5:37:37
* @修改人 Administrator
* @修改时间 2016-5-25下午5:37:37
*/
public static Object Get(Object obj) {
Object ret = obj;
if (obj instanceof JsonNode) {
JsonNode vToken = (JsonNode) obj;
if (vToken instanceof ValueNode) {
ret = ((ValueNode) vToken).asText();
} else {
ret = vToken;
}
}
return ret;
}
/**
* @描述: 根据不同对象输出结果
* @方法名: GetValue
* @param obj
* @param vName
* @return
* @throws Exception
* @返回类型 Object
* @创建人 Administrator
* @创建时间 2016-5-25下午5:39:59
* @修改人 Administrator
* @修改时间 2016-5-25下午5:39:59
*/
public static Object GetValue(Object obj, String vName) throws Exception {
Object ret = null;
if (obj == null) {
return ret;
}
Class vType = obj.getClass();
if (obj instanceof Number || vType.isEnum()) {
ret = null;
} else if (obj instanceof Map) {
ret = ((Map) obj).get(vName);
} else if (obj instanceof ObjectNode) {
return ((ObjectNode) obj).get(vName);
} else {
ret = GetTypeValue(obj.getClass(), obj, vName);
}
return ret;
}
/**
* @描述: 根据不同类型设置不同值
* @方法名: Set
* @param obj
* @param vName
* @param value
* @throws Exception
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-25下午5:46:59
* @修改人 Administrator
* @修改时间 2016-5-25下午5:46:59
*/
public static void Set(Object obj, String vName, Object value) throws Exception {
if (obj == null) {
return;
}
Class vType = obj.getClass();
if (obj instanceof Number || vType.isEnum()) {
return;
} else if (obj instanceof Map) {
((Map) obj).put(vName, value);
} else if (obj instanceof ObjectNode) {
((ObjectNode) obj).put(vName, (JsonNode) value);
} else {
SetTypeValue(vType, obj, vName, value);
}
}
/**
* @描述: 设置对象的值
* @方法名: SetTypeValue
* @param vType
* 要赋值的对象
* @param obj
* @param vName
* 要赋值的方法
* @param value
* 值
* @throws Exception
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-25下午5:48:30
* @修改人 Administrator
* @修改时间 2016-5-25下午5:48:30
*/
public static void SetTypeValue(Class<?> vType, Object obj, String vName, Object value) throws Exception {
try {
Field fie = vType.getField(vName);
int flag = fie.getModifiers();
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (fie != null && isAcc) {
Class<?> vProType = fie.getType();
Object vTypeValue = StringHelper.Get(vProType, value);
fie.set(obj, vTypeValue);
return;
}
} catch (NoSuchFieldException pe) {
String metName = "set" + vName;
Method met = null;
try {
if (value != null) {
met = vType.getMethod(metName, value.getClass());
}
} catch (NoSuchMethodException ex) {
Method[] mets = vType.getMethods();
for (Method item : mets) {
if (!(item.getName().equals(metName) && item.getParameterTypes().length == 1)) {
continue;
}
met = item;
break;
}
}
if (met != null) {
Class vProType = met.getParameterTypes()[0];
Object vTypeValue = StringHelper.Get(vProType, value);
met.invoke(obj, vTypeValue);
}
}
}
/**
* @描述: 获取对象的值从obj中获取关键词为vName的值
* @方法名: GetTypeValue
* @param vType
* 要获取的对象的Class类型
* @param obj
* 要获取的对象
* @param vName
* 要获取的对象的关键词
* @return
* @throws Exception
* @返回类型 Object
* @创建人 Administrator
* @创建时间 2016-5-25下午5:53:57
* @修改人 Administrator
* @修改时间 2016-5-25下午5:53:57
*/
public static Object GetTypeValue(Class<?> vType, Object obj, String vName) throws Exception {
try {
Field fie = vType.getField(vName);
if (fie != null) {
int flag = fie.getModifiers();
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (isAcc) {
}
return fie.get(obj);
}
} catch (Exception ex) {
}
try {
String metName = "get" + vName;
Method met = vType.getMethod(metName);
if (met != null) {
boolean isReturn = met.getReturnType() != null;
int flag = met.getModifiers();
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (isReturn && isAcc) {
return met.invoke(obj);
}
}
} catch (Exception ex) {
}
return null;
}
public static int GetInt(Object obj, String vName) throws Exception {
return Get(Integer.class, obj, vName);
}
public static String GetString(Object obj, String vName) throws Exception {
return Get(String.class, obj, vName);
}
public static BigDecimal GetDecimal(Object obj, String vName) throws Exception {
return Get(BigDecimal.class, obj, vName);
}
/**
* @描述: 类型转换(从obj中取出关键词为vName的值转换为cls类型)
* @方法名: Get
* @param cls
* 转换后的类型
* @param obj
* 要转换对象
* @param vName
* 要转换对象的关键词
* @return
* @throws Exception
* @返回类型 T
* @创建人 Administrator
* @创建时间 2016-5-25下午5:57:10
* @修改人 Administrator
* @修改时间 2016-5-25下午5:57:10
*/
public static <T> T Get(Class<T> cls, Object obj, String vName) throws Exception {
Object val = GetValue(obj, vName);
return StringHelper.Get(cls, val);
}
/**
* @描述: 将集合的类容转换为对象
* @方法名: AddList
* @param vToClass
* 转换后的对象
* @param vTo
* 转换后的对象的集合
* @param vFrom
* 要转换的对象
* @param vField
* 关键词
* @throws Exception
* @返回类型 void
* @创建人 Administrator
* @创建时间 2016-5-25下午6:26:52
* @修改人 Administrator
* @修改时间 2016-5-25下午6:26:52
*/
public static <T> void AddList(Class<T> vToClass, ArrayList<T> vTo, Object vFrom, String vField) throws Exception {
List vFroms = ObjectHelper.Get(List.class, vFrom, vField);
if (vFroms == null || vTo == null) {
return;
}
for (Object vFromItem : vFroms) {
T vToItem = ObjectHelper.Convert(vToClass, vFromItem);
vTo.add(vToItem);
}
}
public static <T> T Convert(T vTo, Object vFrom) throws Exception {
if (vTo == null) {
return null;
}
WriteWithToClass(vTo, vFrom);
return vTo;
}
public static <T> T Convert(Class<T> vToClass, Object vFrom) throws Exception {
T vTo = vToClass.newInstance();
return Convert(vTo, vFrom);
}
/**
* @描述: 对象转换一般将map转为javabean
* @方法名: WriteWithToClass
* @param vTo
* 转换后的对象
* @param vFrom
* 要转换的对象
* @return
* @throws Exception
* @返回类型 Object
* @创建人 Administrator
* @创建时间 2016-5-25下午6:31:09
* @修改人 Administrator
* @修改时间 2016-5-25下午6:31:09
*/
public static Object WriteWithToClass(Object vTo, Object vFrom) throws Exception {
if (vTo == null) {
return null;
}
Class vToType = vTo.getClass();
Method[] vMets = vToType.getMethods();
for (Method vItem : vMets) {
int flag = vItem.getModifiers();
boolean isStatic = (Modifier.FINAL & flag) > 0 || (Modifier.STATIC & flag) > 0;
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (!isAcc || isStatic) {
continue;
}
if (!(vItem.getName().startsWith("set") && vItem.getParameterTypes().length == 1)) {
continue;
}
Class<?> vType = vItem.getParameterTypes()[0];
String vName = vItem.getName().substring(3);
Object vValue = ObjectHelper.Get(vType, vFrom, vName);
try {
if (IsWriteType(vType, vValue)) {
vItem.invoke(vTo, vValue);
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
Field[] vFields = vToType.getFields();
for (Field vItem : vFields) {
int flag = vItem.getModifiers();
boolean isStatic = (Modifier.FINAL & flag) > 0 || (Modifier.STATIC & flag) > 0;
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (!isAcc || isStatic) {
continue;
}
Object vValue = ObjectHelper.Get(vItem.getType(), vFrom, vItem.getName());
try {
if (IsWriteType(vItem.getType(), vValue)) {
vItem.set(vTo, vValue);
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
return vTo;
}
/**
* @描述: 对象转换一般是javabean转map
* @方法名: WriteWithFromClass
* @param vTo
* @param vFrom
* @return
* @throws Exception
* @返回类型 Object
* @创建人 Administrator
* @创建时间 2016-5-25下午6:35:37
* @修改人 Administrator
* @修改时间 2016-5-25下午6:35:37
*/
public static Object WriteWithFromClass(Object vTo, Object vFrom) throws Exception {
if (vFrom == null) {
return vTo;
}
Class vFromType = vFrom.getClass();
Method[] vMets = vFromType.getMethods();
for (Method vItem : vMets) {
int flag = vItem.getModifiers();
boolean isStatic = (Modifier.FINAL & flag) > 0 || (Modifier.STATIC & flag) > 0;
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (!isAcc || isStatic) {
continue;
}
if (!(vItem.getName().startsWith("get") && vItem.getReturnType() != null)) {
continue;
}
Object vValue = vItem.invoke(vFrom);
String vName = vItem.getName().substring(3);
try {
ObjectHelper.Set(vTo, vName, vValue);
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
Field[] vFields = vFromType.getFields();
for (Field vItem : vFields) {
int flag = vItem.getModifiers();
boolean isStatic = (Modifier.FINAL & flag) > 0 || (Modifier.STATIC & flag) > 0;
boolean isAcc = (Modifier.PUBLIC & flag) > 0;
if (!isAcc || isStatic) {
continue;
}
Object vValue = vItem.get(vFrom);
try {
ObjectHelper.Set(vTo, vItem.getName(), vValue);
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
return vTo;
}
/**
* @描述:对象转换
* @方法名: ConvertList
* @param obj
* @return
* @返回类型 List
* @创建人 Administrator
* @创建时间 2016-5-25下午6:43:04
* @修改人 Administrator
* @修改时间 2016-5-25下午6:43:04
*/
public static List ConvertList(List obj) {
List<Object> vList = new ArrayList<Object>();
for (Object item : obj) {
if (item instanceof JsonNode) {
vList.add(DictionaryHelper.ConvertDictionary(item));
} else {
vList.add(item);
}
}
return vList;
}
public static <T> ArrayList<T> GetList(Class<T> cls, Object obj) throws Exception {
ArrayList<T> vTo = new ArrayList<T>();
if (obj instanceof List) {
List vCodeFrom = (List) ((obj instanceof List) ? obj : null);
for (Object vItem : vCodeFrom) {
if (StringHelper.IsEmpty(vItem)) {
continue;
}
T vToItem = StringHelper.Get(cls, vItem);
vTo.add(vToItem);
}
} else {
if (!StringHelper.IsEmpty(obj)) {
T vToItem = StringHelper.Get(cls, obj);
vTo.add(vToItem);
}
}
return vTo;
}
public static boolean IsWriteType(Class<?> a, Object b) {
if (a.isEnum() || a.isAssignableFrom(Number.class)) {
return true;
}
if (a == String.class || a == int.class || a == boolean.class || a == double.class || a == float.class) {
return true;
}
boolean isEmpty = StringHelper.IsEmpty(b);
if (isEmpty) {
return true;
}
return a.isAssignableFrom(b.getClass());
}
public static boolean IsAutoConvert(Class vToType, Class vFromType) {
return vFromType != vToType && (Number.class.isAssignableFrom(vToType) || vToType.isEnum() || vToType == String.class);
}
}

View File

@@ -0,0 +1,35 @@
package com.light.util;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QrHelper {
public static BitMatrix Write(String url, int width, int heigth) throws Exception {
// 判断URL合法性
if (url == null || "".equals(url) || url.length() < 1) {
throw new Exception("生成二维码时,需要生成的字符串不能为空!");
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, heigth, hints);
int[] pixels = new int[width * heigth];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heigth; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
return bitMatrix;
}
}

View File

@@ -0,0 +1,60 @@
package com.light.util;
public class RunInterval
{
/**
当前线程
*/
private Thread Thread;
public Thread getThread()
{
return Thread;
}
public void setThread(Thread value)
{
Thread = value;
}
/**
间隔时间,毫秒
*/
private int Time;
public int getTime()
{
return Time;
}
public void setTime(int value)
{
Time = value;
}
/**
执行的代码
*/
private ThreadDelegateCode Code;
public ThreadDelegateCode getCode()
{
return Code;
}
public void setCode(ThreadDelegateCode value)
{
Code = value;
}
/**
是否终端
*/
private boolean Break;
public boolean getBreak()
{
return Break;
}
public void setBreak(boolean value)
{
Break = value;
}
}

View File

@@ -0,0 +1,46 @@
package com.light.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class StreamWriter {
private PrintWriter pw;
private FileOutputStream fos;
private OutputStreamWriter osw;
public StreamWriter(String vFile, boolean b, String encoding) {
try {
fos = new FileOutputStream(vFile,true);
osw=new OutputStreamWriter(fos, encoding);
if(pw==null){
pw=new PrintWriter(osw,b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void WriteLine(String vResult) {
pw.println(vResult);
}
public void Close() {
try {
if(fos!=null||osw!=null||pw!=null){
fos.close();
osw.close();
pw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,870 @@
package com.light.util;
import java.math.BigDecimal;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.*;
import java.util.*;
/**
* 字符串操作帮助类,传入很多字符串,获取第一个非空的字符串
*/
public class StringHelper {
/**
* MD5加密
*
* @param string
* 源字符串
* @return 加密后的字符串
*/
public static String md5(String string) {
byte[] hash = null;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
/**
* 将字符串转换为 bool 当不能转换时则默认为false
*
* @param vValue
* 需要转换的字符串
* @param vDefault
* 默认值
* @return 转换成功后的值
*/
public static Boolean GetBoolean(Object vValue, boolean vDefault) {
boolean result = vDefault;
try {
if (!StringHelper.IsEmpty(vValue)) {
result = (!StringHelper.SafeCompare(vValue, "0", true) && !StringHelper.SafeCompare(vValue, "false", true)
&& !StringHelper.SafeCompare(vValue, "no", true) && !StringHelper.IsEmpty(vValue));
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
return result;
}
/**
* 将字符串转换为 bool 当不能转换时则默认为false
*
* @param vValue
* 需要转换的字符串
* @return 转换成功后的值
*/
public static Boolean GetBoolean(Object vValue) {
return GetBoolean(vValue, false);
}
/**
* 将字符串转换为 Int当不能转换时则默认为0
*
* @param obj
* 需要转换的字符串
* @return 转换成功后的值
*/
public static short GetShort(Object vValue) {
short result = 0;
try {
if (!StringHelper.IsEmpty(vValue)) {
result = Short.parseShort(vValue.toString());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
/**
* 将字符串转换为 Int当不能转换时则默认为0
*
* @param obj
* 需要转换的字符串
* @return 转换成功后的值
*/
public static Integer GetInt(Object vValue) {
int result = 0;
try {
if (!StringHelper.IsEmpty(vValue)) {
// String类型的小数转int会出错
// double d = Double.parseDouble(vValue.toString());
// int i = (int) d;
// result = Integer.parseInt(String.valueOf(i));
result = Integer.parseInt(vValue.toString());
}
} catch (Exception ex) {
try {
double d = Double.parseDouble(vValue.toString());
int i = (int) d;
result = Integer.parseInt(String.valueOf(i));
} catch (Exception e) {
LogHelper.WriteLog(e, StringHelper.GetString(vValue));
}
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
public static Long GetLong(Object vValue) {
long result = 0;
try {
if (!StringHelper.IsEmpty(vValue)) {
result = Long.parseLong(vValue.toString());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
public static long GetLong(byte[] bytes) {
if (bytes.length > 0) {
return ByteConvertHelper.lBytesToLong(bytes, 0);
}
return 0;
}
public static String GetPrice(Object obj) {
String str = "-";
if (!IsEmpty(obj) && GetDouble(obj) != 0) {
str = "" + GetDouble(obj);
}
return str;
}
/**
* 将字符串转换为 Float当不能转换时则默认为0
*
* @param obj
* 需要转换的字符串
* @return 转换成功后的值
*/
public static float GetFloat(Object vValue) {
float result = 0;
try {
if (!StringHelper.IsEmpty(vValue)) {
result = Float.parseFloat(vValue.toString());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
/**
* 将字符串转换为 Double当不能转换时则默认为0
*
* @param obj
* 需要转换的字符串
* @return 转换成功后的值
*/
public static Double GetDouble(Object vValue) {
double result = 0.0;
try {
if (!StringHelper.IsEmpty(vValue)) {
result = Double.parseDouble(vValue.toString());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
/**
* 将字符串转换为Decimal当不能转换时则默认值为0
*
* @param vValue
* 需要转换的字符串
* @return 转换成功后的值
*/
public static java.math.BigDecimal GetDecimal(Object vValue) {
java.math.BigDecimal result = new java.math.BigDecimal(0);
try {
if (!StringHelper.IsEmpty(vValue)) {
result = new BigDecimal(vValue.toString());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex, StringHelper.GetString(vValue));
}
return result;
}
/**
* 将 object 转换为String
*
* @param obj
* 需要转换的object
* @return 转换成功的字符串
*/
public static String GetString(Object obj) {
obj = ObjectHelper.Get(obj);
return obj == null ? null : obj.toString();
}
private static String[] m_formats = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" };
public static Date GetDateTime(Object s) throws ParseException {
if (s == null) {
return null;
}
if (s instanceof Date) {
return (Date) (s);
} else if (s instanceof Date) {
return (Date) ((s instanceof Date) ? s : null);
}
String strValue = StringHelper.GetString(s).replace("T", " ");
Date date = null;
if (!isNullOrEmpty(strValue)) {
// 第一次处理
try {
date = new Date(Date.parse(strValue));
} catch (Exception ex) {
LogHelper.WriteLog(ex, strValue);
}
// 采用格式处理
if (date == null) {
for (int i = 0; i < m_formats.length; i++) {
try {
date = new SimpleDateFormat(m_formats[i]).parse(strValue);
} catch (Exception ex) {
LogHelper.WriteLog(ex, strValue);
}
if (date != null) {
break;
}
}
}
}
return date;
}
/**
* 根据类型来获取值
*
* @param vType
* 类型
* @param fieldValue
* 对象
* @return 返回获取的值
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T> T Get(Class<T> vType, Object fieldValue) throws Exception {
String vName = vType.getName();
if (vType.isEnum()) {
String strValue = StringHelper.GetString(fieldValue);
return EnumHelper.ConvertEnum(vType, strValue);
} else if (IsType(vType, String.class)) {
return (T) StringHelper.GetString(fieldValue);
} else if ("boolean".equals(vName) || IsType(vType, Boolean.class)) {
String strValue = StringHelper.GetString(fieldValue);
return (T) StringHelper.GetBoolean(strValue);
} else if ("int".equals(vName) || IsType(vType, Integer.class)) {
return (T) StringHelper.GetInt(fieldValue);
} else if ("double".equals(vName) || IsType(vType, Double.class)) {
return (T) StringHelper.GetDouble(fieldValue);
} else if ("float".equals(vName) || IsType(vType, Float.class)) {
return (T) StringHelper.GetDouble(fieldValue);
} else if (IsType(vType, BigDecimal.class)) {
return (T) StringHelper.GetDecimal(fieldValue);
} else if (IsType(vType, Date.class)) {
return (T) StringHelper.GetDateTime(fieldValue);
}
return (T) fieldValue;
}
public static byte[] GetByte(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
int btvalue = Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
bytes[i] = (byte) btvalue;
}
return bytes;
}
public static byte ToBCD(int p) throws Exception {
if (p >= 100) {
throw new Exception("整形转换成字节的PCD码必须小于100");
}
byte bt = (byte) ((p / 10 * 16) + p % 10);
return bt;
}
public static int FromBCD(byte bt) {
return (bt / 16) * 10 + bt % 16;
}
public static String GetStringByte(byte[] bytes) {
return GetStringByte(bytes, 0);
}
public static String GetStringByte(byte[] bytes, int len) {
if (len == 0) {
len = bytes.length;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
byte by = bytes[i];
sb.append(String.format("%02X", by));
}
return sb.toString();
}
/**
* 使用Unicode转码
*
* @param str
* @return
*/
public static String EncodingString(String str) {
return EncodingString("UTF-8", str);
}
/**
* 字符串编码转换
*
* @param str
* 输入字符串
* @return
*/
public static String EncodingString(String encoding, String str) {
byte[] buff;
try {
buff = str.getBytes(encoding);
str = new String(buff); // 将字节流转换为字符串
str = str.replace("\0", "").replace("\n", "");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return str;
}
/**
* 传入很多字符串,获取第一个非空的字符串,至少需要两个参数
*
* @param obj0
* 第一个参数
* @param obj1
* 第二个参数
* @param obj2
* 参数列表
* @return 第一个非空字符串
*/
public static String GetLastString(String obj0, String obj1, String... obj2) {
if (!isNullOrEmpty(obj0)) {
return obj0;
}
if (!isNullOrEmpty(obj1)) {
return obj1;
}
for (String str : obj2) {
if (!isNullOrEmpty(str)) {
return str;
}
}
return "";
}
public static String GetTrim(String vCode) {
if (vCode == null) {
return null;
}
return vCode.trim();
}
/**
* 获取名称,当第一个值为空时,则返回第二个值,否则返回第一个值
*
* @param vName
* 第一个值
* @param vDefaultName
* 需要代替的值
* @return 返回不为空的值
*/
public static String GetDefaultName(String vName, String vDefaultName) {
if (isNullOrEmpty(vName)) {
return vDefaultName;
}
return vName;
}
public static String GetDateTimeString(String p, Date vLastTime) {
String vEmpty = "";
if (vLastTime != null) {
vEmpty = new SimpleDateFormat(p).format(vLastTime);
}
return vEmpty;
}
public static String GetStringLen(double data, int vLen) {
return GetStringLen(data, vLen, "0");
}
public static String GetStringLen(double data, int vLen, String c) {
String vIndex = data + "";// (new Double(data)).toString();
for (int i = vIndex.length(); i < vLen; i++) {
vIndex = c + vIndex;
}
return vIndex;
}
public static String GetStringLenLast(double data, int vLen, String c) {
String vIndex = data + "";// (new Double(data)).toString();
for (int i = vIndex.length(); i < vLen; i++) {
vIndex = vIndex + c;
}
return vIndex;
}
/**
* 将数组转换为字符串
*
* @param vStrs
* 需要转换的数组
* @return 转换成功后的字符串
*/
public static String ArrayToString(String[] vStrs) {
StringBuilder stringBuilder = new StringBuilder();
int i;
for (i = 0; i < vStrs.length - 1; i++) {
stringBuilder.append(vStrs[i].replace("@", "@@"));
stringBuilder.append("<@>");
}
stringBuilder.append(vStrs[i].replace("@", "@@"));
return stringBuilder.toString();
}
/**
* 将字符串转换为数组
*
* @param vStr
* 需要转换的字符串
* @return 转换成功后的数组
*/
public static String[] StringToArray(String vStr) {
String text = "<@>";
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
int num = 0;
int num2;
while ((num2 = vStr.indexOf(text, num)) != -1) {
String item = vStr.substring(num, num2).replace("@@", "@");
list.add(item);
num = num2 + text.length();
}
String item2 = vStr.substring(num).replace("@@", "@");
list.add(item2);
return list.toArray(new String[] {});
}
/**
* 比较两个字符串是否相等
*
* @param string1
* 字符串1
* @param string2
* 字符串2
* @param ignoreCase
* 是否区分大小写
* @return 比较结果
*/
public static boolean SafeCompare(String string1, String string2, boolean ignoreCase) {
if (string1 == null && string2 == null) {
return true;
} else if (string1 == null || string2 == null) {
return false;
} else if (string1.length() != string2.length()) {
return false;
} else if (ignoreCase) {
return string1.compareToIgnoreCase(string2) == 0;
} else {
return string1.compareTo(string2) == 0;
}
}
/**
* 比较两个对象转换为字符串是否相等
*
* @param a
* 字符串1
* @param b
* 字符串2
* @param ignoreCase
* 是否区分大小写
* @return 比较结果
*/
public static boolean SafeCompare(Object a, Object b, boolean ignoreCase) {
String aStr = "";
String bStr = "";
if (a != null) {
aStr = a.toString();
}
if (b != null) {
bStr = b.toString();
}
return SafeCompare(aStr, bStr, ignoreCase);
}
/**
* 检测字符是否为空
*
* @param p
* 需要检测的字符
* @return 检测结果
*/
public static boolean IsEmptyChar(char p) {
if (p == '\r' || p == '\n' || p == '\t' || p == ' ') {
return true;
}
return false;
}
/**
* 类型匹配
*
* @param type
* 类型
* @param typeName
* 类型的名称
* @return 读取的结果
*/
public static boolean IsType(Class<?> type, Class<?> vBase) {
if (type == null) {
return false;
} else if (type.equals(vBase)) {
return true;
}
if (type.toString().equals("System.Object")) {
return false;
} else {
return IsType(type.getSuperclass(), vBase);
}
}
public static boolean IsEmpty(Object vValue) {
return vValue == null || isNullOrEmpty(vValue.toString());
}
/**
* 比较时间
*
* @param nullable
* @param vNow
* @return
*/
public static int CompareDate(Date nullable, Date vNow) {
if (nullable == null || nullable == null) {
return 2;
}
if (nullable.getTime() > vNow.getTime()) {
return 1;
} else if (nullable.getTime() < vNow.getTime()) {
return -1;
} else {
return 0;
}
}
public static int GetPage(int p1, int p2) {
if (p2 != 0) {
return p1 / p2 + (p1 % p2 > 0 ? 1 : 0);
}
return 0;
}
public static String GetGo(String... args) {
StringBuilder sb = new StringBuilder();
for (String vStr : args) {
if (isNullOrEmpty(vStr)) {
continue;
}
if (sb.length() > 0) {
sb.append(" => ");
}
sb.append(vStr);
}
return sb.toString();
}
/**
* DES加密字符串
*
* @param vKey
* 密匙
* @param encryptString
* 待加密的字符串
* @param encryptKey
* 加密密钥,要求为8位
* @return 加密成功返回加密后的字符串,失败返回源串
* @throws Exception
*/
public static String EncryptDES(byte[] vKey, String encryptString, String encryptKey) throws Exception {
if (!isNullOrEmpty(encryptString)) {
// byte[] rgbKey = encryptKey.substring(0,
// 8).getBytes("UTF-8");//Encoding.UTF8.GetBytes(encryptKey.substring(0,
// 8));
// byte[] rgbIV = vKey;
// byte[] inputByteArray =
// encryptString.getBytes("UTF-8");//Encoding.UTF8.GetBytes(encryptString);
// DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
// ByteArrayOutputStream mStream = new ByteArrayOutputStream();
// CryptoStream cStream = new CryptoStream(mStream,
// dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
// cStream.Write(inputByteArray, 0, inputByteArray.length);
// cStream.FlushFinalBlock();
String str = DesHelper.encode(vKey, encryptString, encryptKey);
return str;// Convert.ToBase64String(mStream.toByteArray());
}
return "";
}
/**
* DES解密字符串
*
* @param decryptString
* 待解密的字符串
* @param decryptKey
* 解密密钥,要求为8位,和加密密钥相同
* @return 解密成功返回解密后的字符串,失败返源串
* @throws Exception
* @throws IOException
*/
public static String DecryptDES(byte[] vKey, String decryptString, String decryptKey) throws IOException, Exception {
if (!isNullOrEmpty(decryptString)) {
// byte[] rgbKey =
// decryptKey.getBytes("UTF-8");//Encoding.UTF8.GetBytes(decryptKey);
// byte[] rgbIV = vKey;
// byte[] inputByteArray = Base64.decode(decryptString,
// Base64.DEFAULT);//Convert.FromBase64String(decryptString);
// DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
// ByteArrayOutputStream mStream = new ByteArrayOutputStream();
// CryptoStream cStream = new CryptoStream(mStream,
// DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
// cStream.Write(inputByteArray, 0, inputByteArray.length);
// cStream.FlushFinalBlock();
// byte[] bytes = mStream.toByteArray();
String str = DesHelper.decode(vKey, decryptString, decryptKey);
return str;// Encoding.UTF8.GetString(bytes, 0, bytes.length);
}
return "";
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'IsNullOrEmpty'.
// ------------------------------------------------------------------------------------
public static boolean isNullOrEmpty(String string) {
return string == null || string.equals("");
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'Join' (2 parameter
// version).
// ------------------------------------------------------------------------------------
public static String join(String separator, String[] stringarray) {
if (stringarray == null)
return null;
else
return join(separator, stringarray, 0, stringarray.length);
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'Join' (4 parameter
// version).
// ------------------------------------------------------------------------------------
public static String join(String separator, String[] stringarray, int startindex, int count) {
String result = "";
if (stringarray == null)
return null;
for (int index = startindex; index < stringarray.length && index - startindex < count; index++) {
if (separator != null && index > startindex)
result += separator;
if (stringarray[index] != null)
result += stringarray[index];
}
return result;
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'TrimEnd'.
// ------------------------------------------------------------------------------------
public static String trimEnd(String string, Character... charsToTrim) {
if (string == null || charsToTrim == null)
return string;
int lengthToKeep = string.length();
for (int index = string.length() - 1; index >= 0; index--) {
boolean removeChar = false;
if (charsToTrim.length == 0) {
if (Character.isWhitespace(string.charAt(index))) {
lengthToKeep = index;
removeChar = true;
}
} else {
for (int trimCharIndex = 0; trimCharIndex < charsToTrim.length; trimCharIndex++) {
if (string.charAt(index) == charsToTrim[trimCharIndex]) {
lengthToKeep = index;
removeChar = true;
break;
}
}
}
if (!removeChar)
break;
}
return string.substring(0, lengthToKeep);
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'TrimStart'.
// ------------------------------------------------------------------------------------
public static String trimStart(String string, Character... charsToTrim) {
if (string == null || charsToTrim == null)
return string;
int startingIndex = 0;
for (int index = 0; index < string.length(); index++) {
boolean removeChar = false;
if (charsToTrim.length == 0) {
if (Character.isWhitespace(string.charAt(index))) {
startingIndex = index + 1;
removeChar = true;
}
} else {
for (int trimCharIndex = 0; trimCharIndex < charsToTrim.length; trimCharIndex++) {
if (string.charAt(index) == charsToTrim[trimCharIndex]) {
startingIndex = index + 1;
removeChar = true;
break;
}
}
}
if (!removeChar)
break;
}
return string.substring(startingIndex);
}
// ------------------------------------------------------------------------------------
// This method replaces the .NET static string method 'Trim' when arguments
// are used.
// ------------------------------------------------------------------------------------
public static String trim(String string, Character... charsToTrim) {
return trimEnd(trimStart(string, charsToTrim), charsToTrim);
}
// ------------------------------------------------------------------------------------
// This method is used for string equality comparisons when the option
// 'Use helper 'stringsEqual' method to handle null strings' is selected
// (The Java String 'equals' method can't be called on a null instance).
// ------------------------------------------------------------------------------------
public static boolean stringsEqual(String s1, String s2) {
if (s1 == null && s2 == null)
return true;
else
return s1 != null && s1.equals(s2);
}
public static String[] Split(String vStr, String regex) {
return vStr.split(regex);
}
/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static String GetGUID() {
return UUID.randomUUID().toString().trim().replaceAll("-", "");
}
public static void subStringException(String local, int start, int end, int allsize, String str) throws Exception {
String exception = local + "/n" + "开始:" + start + " 结束:" + end + "总长:" + allsize + "/n" + str;
throw new Exception(exception);
}
/**
* 获取小时的时间
*
* @param dt
* @return
* @throws ParseException
*/
public static CharSequence GetHour(String sdt) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date dt = format.parse(sdt);
return format.format(dt);
}
/**
* 获取空字符串
*
* @param str
* @return
*/
public static String GetEmpty(Object str) {
if (IsEmpty(str)) {
return "";
}
return str.toString();
}
private static SimpleDateFormat formatday = new SimpleDateFormat("yyyy-MM-dd");
/**
* 获取当前日期
*
* @param date
* @return
*/
public static String GetDay(Date date) {
return formatday.format(date);
}
/**
* 获取当前日期
*
* @param date
* @return
*/
public static String GetDay(String date) {
try {
return formatday.format(formatday.parse(date));
} catch (ParseException e) {
LogHelper.WriteLog(e);
return "";
}
}
}

View File

@@ -0,0 +1,168 @@
package com.light.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Scanner;
/**
* 获取设置信息
*
* @author Light
*
*/
public class SystemHard {
/**
* 移动
*/
public static final int NetYidong = 1;
/**
* 联通
*/
public static final int NetLiantong = 2;
/**
* 电信
*/
public static final int NetDianxin = 3;
/**
* 执行底层命令
*
* @param cmd
* @return
* @throws IOException
*/
public static String do_exec(String cmd) throws IOException {
String s = "";
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
s += line + "\n";
}
return s;
}
/**
* 获取CPU编号
*
* @return @throws
*/
public static String GetCommandCPU() {
String ret = "";
try {
ret = do_exec("cat /proc/cpuinfo").trim();
} catch (Exception ex) {
ex.printStackTrace();
}
return ret;
}
/**
* 获取CPU编号
*
* @return @throws
*/
public static String GetCommandMac() {
String ret = "";
try {
ret = do_exec("cat /sys/class/net/wlan0/address").trim();
} catch (Exception ex) {
ex.printStackTrace();
}
return ret;
}
/**
* 设备编号
*
* @param loadActivity
* @return
*/
public static String GetHardID(Object act) {
String vFrom = act.getClass().getPackage().getName() + GetCommandCPU() + GetCommandMac() + GetWindowCPUID()
+ GetWiddowHardwardID() + GetWindowMac();
String vTo = StringHelper.md5(vFrom);
return vTo;
}
/**
* 获取Windows CPU 编号
*
* @return
*/
private static String GetWindowCPUID() {
try {
// long start = System.currentTimeMillis();
Process process = Runtime.getRuntime().exec(new String[] { "wmic", "cpu", "get", "ProcessorId" });
process.getOutputStream().close();
Scanner sc = new Scanner(process.getInputStream());
String property = sc.next();
String serial = sc.next();
return serial;
} catch (Exception ex) {
LogHelper.WriteLog(ex);
return "";
}
}
/**
* 获取Windows 硬盘序列号
*
* @return
*/
private static String GetWiddowHardwardID() {
String line = "";
String HdSerial = "";// 记录硬盘序列号
try {
Process proces = Runtime.getRuntime().exec("cmd /c dir c:");// 获取命令行参数
BufferedReader buffreader = new BufferedReader(new InputStreamReader(proces.getInputStream()));
while ((line = buffreader.readLine()) != null) {
if (line.indexOf("卷的序列号是 ") != -1) { // 读取参数并获取硬盘序列号
HdSerial = line.substring(line.indexOf("卷的序列号是 ") + "卷的序列号是 ".length(), line.length());
break;
}
}
} catch (IOException e) {
LogHelper.WriteLog(e);
}
return HdSerial; // 返回硬盘序列号
}
/**
* 获取Windows MAC地址
*
* @return
* @throws SocketException
*/
private static String GetWindowMac() {
try {
byte[] mac = NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress();
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
// 字节转换为整数
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
} catch (Exception ex) {
LogHelper.WriteLog(ex);
return "";
}
}
}

View File

@@ -0,0 +1,5 @@
package com.light.util;
public interface ThreadDelegateCode {
void Execute() throws Exception;
}

View File

@@ -0,0 +1,12 @@
package com.light.util;
public class ThreadDelegateCodeExecute implements IEventExecute<ThreadDelegateCode>{
@Override
public void Execute(ThreadDelegateCode t) throws Exception {
t.Execute();
}
}

View File

@@ -0,0 +1,465 @@
package com.light.util;
import java.util.*;
public class ThreadHelper {
private static Object _ThreadLock = new Object();
private static Thread _Thread = null;
private static Date _ThreadDate = null;
private static ExecuteRun Timeout;
private static ExecuteRun Interval;
private static void InitStatic() {
_ThreadDate = new Date("1987-11-04");
Timeout = new ExecuteRun();
Interval = new ExecuteRun();
ThreadDelegateCode vAdd = new ThreadDelegateCode() {
@Override
public void Execute() {
OnExecuteAdd();
}
};
ThreadDelegateCode vItemAdd = new ThreadDelegateCode() {
@Override
public void Execute() {
OnItemExecuted();
}
};
Timeout.OnAdd.Add(vAdd);
Timeout.OnItemExecuted.Add(vItemAdd);
Interval.OnAdd.Add(vAdd);
Interval.OnItemExecuted.Add(vItemAdd);
StartMonitor();
}
// #region 内部累
private static class ExecuteData {
public Date Date;
public double ExecuteCount;
public double ExecuteError; // 调试变量
public String Flag;
public int Time;
public ThreadDelegateCode Execute;
public ExecuteData() {
this.Date = new java.util.Date();
}
}
public static class ExecuteRun {
private Object m_Lock = new Object();
private java.util.ArrayList<ExecuteData> m_List = new java.util.ArrayList<ExecuteData>();
private Event<ThreadDelegateCode> OnAdd = new Event<ThreadDelegateCode>();
private Event<ThreadDelegateCode> OnRemove = new Event<ThreadDelegateCode>();
private Event<ThreadDelegateCode> OnItemExecuted = new Event<ThreadDelegateCode>();
private Event<ThreadDelegateCode> OnExecuted = new Event<ThreadDelegateCode>();
public Event<ThreadDelegateCode> GetOnAdd() {
return OnAdd;
}
public Event<ThreadDelegateCode> GetOnRemove() {
return OnRemove;
}
public Event<ThreadDelegateCode> GetOnItemExecuted() {
return OnItemExecuted;
}
public Event<ThreadDelegateCode> GetOnExecuted() {
return OnExecuted;
}
/**
* 执行完任务后,是否需要删除该任务,并且设置允许执行的最大错误
*
* @param vIsRemove
* @param vMaxError
*/
public final void Execute(boolean vIsRemove, int vMaxError) {
for (int i = m_List.size() - 1; i >= 0; i--) {
Date vNow = new Date();
ExecuteData vItem = null;
synchronized (this.m_Lock) {
vItem = m_List.size() > i ? m_List.get(i) : null;
}
if (vItem == null) {
continue;
}
double vMillseconds = 0;
// 在Window CE中时间相减可能会出错
try {
// 处理非法改动时间
if (vItem.Date.compareTo(vNow) > 0) {
vItem.Date = vNow;
}
vMillseconds = (vNow.getTime() - vItem.Date.getTime());
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
// 未到执行时间
if (vMillseconds <= vItem.Time) {
continue;
}
if (vMaxError == -1 || vItem.ExecuteError < vMaxError) {
try {
vItem.ExecuteCount++;
vItem.ExecuteError++;
vItem.Execute.Execute();
vItem.ExecuteError = 0;
this.ExecuteEvent(this.OnItemExecuted);
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
vItem.Date = new java.util.Date();
}
try {
if (vIsRemove) {
synchronized (this.m_Lock) {
this.m_List.remove(i);
this.ExecuteEvent(this.OnRemove);
}
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
this.ExecuteEvent(this.OnExecuted);
}
/**
* 设置需要执行的任务
*
* @param vFrom
* 需要执行的窗体
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
// public final String Set(Form vForm, ThreadDelegateCode vExecute, int
// vTime)
// {
// final String flag = Set(vExecute, vTime);
// vForm.getOnFinish().Add(new DelegateCode()
// {
// @Override
// public void Execute()
// {
// Clear(flag);
// }
// });
// return flag;
// }
/**
* 设置需要执行的任务
*
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
public final String Set(ThreadDelegateCode vExecute, int vTime) {
ExecuteData tempVar = new ExecuteData();
tempVar.Flag = UUID.randomUUID().toString().replace("-", "");// Guid.NewGuid().ToString("N");
tempVar.Execute = vExecute;
tempVar.Time = vTime;
ExecuteData vData = tempVar;
synchronized (m_Lock) {
m_List.add(vData);
}
this.ExecuteEvent(this.OnAdd);
return vData.Flag;
}
/**
* 清除需要执行的任务
*
* @param flag
* 执行标志
*/
public final void Clear(String flag) {
synchronized (m_Lock) {
for (ExecuteData item : this.m_List) {
if (item.Flag.equals(flag)) {
this.m_List.remove(item);
this.ExecuteEvent(this.OnRemove);
break;
}
}
}
}
/**
* 清除需要执行的任务
*
* @param vExecute
* 执行的方法,注意有多个同样的方法时,只会清除第一个
*/
public final void Clear(ThreadDelegateCode vExecute) {
synchronized (m_Lock) {
for (ExecuteData item : this.m_List) {
if (item.Execute == vExecute) {
this.m_List.remove(item);
this.ExecuteEvent(this.OnRemove);
break;
}
}
}
}
private void ExecuteEvent(Event<ThreadDelegateCode> vExecute) {
try {
if (vExecute != null) {
vExecute.Exeucte(new ThreadDelegateCodeExecute());
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
}
public final int getCount() {
return this.m_List.size();
}
}
private static void OnItemExecuted() {
_ThreadDate = new java.util.Date();
}
private static void OnExecuteAdd() {
StartThread();
}
private static void StartThread() {
synchronized (_ThreadLock) {
if (_Thread != null) {
return;
}
_Thread = ThreadHelper.RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
while (true) {
try {
Timeout.Execute(true, -1);
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
try {
Interval.Execute(false, -1);
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
if (Timeout.getCount() == 0 && Interval.getCount() == 0) {
break;
}
Thread.sleep(10);
}
_Thread = null;
}
});
}
}
static {
// InitStatic();
}
/**
* 监控线程的方法,防止线程执行死机
*/
private static void StartMonitor() {
ThreadHelper.RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
do {
if (_Thread != null && ((new java.util.Date().getTime() - _ThreadDate.getTime()) / 1000) > 5) {
try {
if (_Thread != null) {
_Thread.stop();
}
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
_Thread = null;
StartThread();
}
Thread.sleep(1000 * 60);
} while (true);
}
});
}
/**
* 多少毫秒后执行任务,适用于执行时间短,不需要单独开线程的程序
*
* @param vFrom
* 需要执行的窗体
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
// public static String SetTimeout(Form vForm, ThreadDelegateCode vExecute,
// int vTime)
// {
// return Timeout.Set(vForm, vExecute, vTime);
// }
/**
* 多少毫秒后执行任务,适用于执行时间短,不需要单独开线程的程序
*
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
public static String SetTimeout(ThreadDelegateCode vExecute, int vTime) {
return Timeout.Set(vExecute, vTime);
}
/**
* 清除需要执行的任务
*
* @param flag
* 执行标志
*/
public static void ClearTimeout(String flag) {
Timeout.Clear(flag);
}
/**
* 清除需要执行的任务
*
* @param vExecute
* 执行的方法,注意有多个同样的方法时,只会清除第一个
*/
public static void ClearTimeout(ThreadDelegateCode vExecute) {
Timeout.Clear(vExecute);
}
/**
* 每隔多少毫秒执行任务,适用于执行时间短,不需要单独开线程的程序
*
* @param vFrom
* 需要执行的窗体
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
// public static String SetInterval(Form vForm, ThreadDelegateCode vExecute,
// int vTime)
// {
// return Interval.Set(vForm, vExecute, vTime);
// }
/**
* 每隔多少毫秒执行任务,适用于执行时间短,不需要单独开线程的程序
*
* @param vExecute
* 需要执行的程序
* @param vTime
* 间隔时间
* @return 执行标志
*/
public static String SetInterval(ThreadDelegateCode vExecute, int vTime) {
return Interval.Set(vExecute, vTime);
}
/**
* 清除需要执行的任务
*
* @param flag
* 执行标志
*/
public static void ClearInterval(String flag) {
Interval.Clear(flag);
}
/**
* 清除需要执行的任务
*
* @param vExecute
* 执行的方法,注意有多个同样的方法时,只会清除第一个
*/
public static void ClearInterval(ThreadDelegateCode vExecute) {
Interval.Clear(vExecute);
}
public static void Sleep(int p) throws InterruptedException {
Thread.sleep(p);
}
public static Thread RunThread(final ThreadDelegateCode vExecute) {
Thread thread = new Thread() {
@Override
public void run() {
try {
vExecute.Execute();
} catch (Exception ex) {
ex.printStackTrace();
LogHelper.WriteLog(ex);
}
}
};
thread.setDaemon(true);
thread.start();
return thread;
}
public static Thread RunThread(final RunInterval vInterval) {
Thread vThread = RunThread(new ThreadDelegateCode() {
@Override
public void Execute() throws Exception {
while (!vInterval.getBreak()) {
try {
vInterval.getCode().Execute();
} catch (Exception ex) {
LogHelper.WriteLog(ex);
}
Thread.sleep(vInterval.getTime());
}
}
});
vInterval.setThread(vThread);
return vThread;
}
public static void sleep(int timer) {
try {
Thread.sleep(timer);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@@ -0,0 +1,78 @@
package com.light.util;
public class Uint32 {
public final static int SIZE = 32;
private final static long MIN = 0L;
private final static long MAX = (1L << SIZE) - 1;
public final static Uint32 MIN_VALUE = new Uint32(MIN);
public final static Uint32 MAX_VALUE = new Uint32(MAX);
private Long value;
public Uint32() {
this(0L);
}
public Uint32(long value) {
setValue(value);
}
public Uint32(int value) {
if (value < 0) {
setValue(value - Integer.MIN_VALUE + (long) Integer.MAX_VALUE + 1);
} else {
setValue(value);
}
}
public long getValue() {
return value;
}
public void setValue(long value) {
check(value);
this.value = value & MAX;
}
private void check(long value) {
if (value < MIN || value > MAX) {
throw new IllegalArgumentException(value + " 值必须在 " + MIN + "" + MAX + " 之间");
}
}
@Override
public int hashCode() {
return ((Long) value).hashCode();
}
public String toString() {
return String.valueOf(value);
}
public int compareTo(Uint32 obj) {
if (obj == null) {
return -1;
}
if (this.value == obj.value) {
return 0;
}
return this.value > obj.value ? 1 : 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Uint32 other = (Uint32) obj;
if (value != other.value)
return false;
return true;
}
}

View File

@@ -0,0 +1,27 @@
package com.light.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class UrlUtil {
// 转换为%E4%BD%A0形式
public static String Encoding(String s, String encoding) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
String t = URLEncoder.encode("" + c, encoding);
sb.append(t);
}
}
return sb.toString();
}
// 将%E4%BD%A0转换为汉字
public static String Decoding(String s, String encoding) throws UnsupportedEncodingException {
return URLDecoder.decode(s, encoding);
}
}

84
src/test/DES3.java Normal file
View File

@@ -0,0 +1,84 @@
package test;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DES3 {
public static final String ALGORITHM_TAG = "BC";
public static final String ALGORITHM = "DESede/ECB/PKCS7Padding";
public static final String ALGORITHM_KEY = "DESede"; // 定义 加密算法,可用
// DES,DESede,Blowfish
// AES
static {
// 初始化
Security.addProvider(new BouncyCastleProvider());
}
private byte[] Handle(int type, byte[] from, String key, String siv) throws Exception {
if (key.length() < 24) {
key += "000000000000000000000000000000000";
}
key = key.substring(0, 24);
byte[] keys = key.getBytes("UTF-8");
SecretKey secretKey = new SecretKeySpec(keys, ALGORITHM_KEY);
Cipher cipher = isEmpty(ALGORITHM_TAG) ? Cipher.getInstance(ALGORITHM)
: Cipher.getInstance(ALGORITHM, ALGORITHM_TAG);
if (ALGORITHM.indexOf("/ECB/") > 0 || isEmpty(siv)) {
cipher.init(type, secretKey);
} else {
byte[] ivs = siv.getBytes("UTF-8");
IvParameterSpec iv = new IvParameterSpec(ivs);
cipher.init(type, secretKey, iv);
}
byte[] to = cipher.doFinal(from);
return to;
}
private boolean isEmpty(String str) {
return str == null || str.equals("");
}
// 解密数据
public String decrypt(String fromString, String key, String siv) throws Exception {
BASE64Decoder base64 = new BASE64Decoder();
byte[] from = base64.decodeBuffer(fromString);
byte[] to = Handle(Cipher.DECRYPT_MODE, from, key, siv);
String toString = new String(to, "UTF-8");
return toString;
}
public String encrypt(String fromString, String key, String siv) throws Exception {
byte[] from = fromString.getBytes("UTF-8");
byte[] to = Handle(Cipher.ENCRYPT_MODE, from, key, siv);
// Base64 加密实例
BASE64Encoder base64 = new BASE64Encoder();
String toString = base64.encode(to);
return toString;
}
public static void main(String[] args) throws Exception {
String sIV = "hellocxp";
String key = "15874498990";
String value = "96e63ae1-336b-4638-be20-5e2ac73bf2e3";
DES3 des = new DES3();
System.out.println("加密数据:" + value);
String a = des.encrypt(value, key, sIV);
System.out.println("加密后的数据为:" + a);
String b = des.decrypt(a, key, sIV);
System.out.println("解密后的数据:" + b);
}
}

View File

@@ -0,0 +1,169 @@
package test;
import java.io.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import sun.misc.BASE64Encoder;
public class DesPKCS7Encrypter {
private static final String Algorithm = "DESede"; // 定义 加密算法,可用
// DES,DESede,Blowfish
Cipher ecipher;
Cipher dcipher;
DesPKCS7Encrypter(byte[] keyBytes, byte[] ivBytes) throws Exception {
Init(keyBytes, ivBytes);
}
DesPKCS7Encrypter(DESKeySpec keySpec, IvParameterSpec ivSpec) throws Exception {
Init(keySpec, ivSpec);
}
private void Init(byte[] keyBytes, byte[] ivBytes) throws Exception {
SecretKey key = new SecretKeySpec(keyBytes, Algorithm);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
Init(key, iv);
}
private void Init(DESKeySpec keySpec, IvParameterSpec iv) throws Exception {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Init(key, iv);
}
private void Init(SecretKey key, IvParameterSpec iv) throws Exception {
AlgorithmParameterSpec paramSpec = iv;
try {
ecipher = Cipher.getInstance(Algorithm + "/CBC/NoPadding");
dcipher = Cipher.getInstance(Algorithm + "/CBC/NoPadding");
// CBC requires an initialization vector
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (Exception e) {
throw e;
}
}
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
byte[] buf = new byte[this.ecipher.getBlockSize()];
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while (true) {
numRead = in.read(buf);
boolean bBreak = false;
if (numRead == -1 || numRead < buf.length) {
int pos = numRead == -1 ? 0 : numRead;
byte byteFill = (byte) (buf.length - pos);
for (int i = pos; i < buf.length; ++i) {
buf[i] = byteFill;
}
bBreak = true;
}
out.write(buf);
if (bBreak)
break;
}
out.close();
} catch (java.io.IOException e) {
System.out.println("Exception e in encrypt=" + e);
}
}
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
byte[] buf = new byte[this.dcipher.getBlockSize()];
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
if (in.available() > 0) {
out.write(buf, 0, numRead);
} else {
byte byteBlock = buf[buf.length - 1];
int i = 0;
for (i = buf.length - byteBlock; i >= 0 && i < buf.length; ++i) {
if (buf[i] != byteBlock) {
break;
}
}
if (i == buf.length) {
out.write(buf, 0, buf.length - byteBlock);
} else {
out.write(buf);
}
}
}
out.close();
} catch (java.io.IOException e) {
System.out.println("Exception e in decrypt=" + e);
}
}
public static String encrypt(String value, String key, String siv) throws Exception {
if (key.length() < 24) {
key += "000000000000000000000000000000000";
}
key = key.substring(0, 24);
// 生成Key和IV
byte[] byteKey = key.getBytes("UTF-8");
byte[] byteIv = siv.getBytes("UTF-8");
// 创建加密实例
DesPKCS7Encrypter encrypter = new DesPKCS7Encrypter(byteKey, byteIv);
// 生成要加密的数据
ByteArrayInputStream bais = new ByteArrayInputStream(value.getBytes("UTF-8"));
// 声明加密输出
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Base64 加密实例
BASE64Encoder base64Encoder = new BASE64Encoder();
// 加密
encrypter.encrypt(bais, baos);
// Base64加密
String outStr = base64Encoder.encode(baos.toByteArray());
return outStr;
}
public String decrypt(String value, String key, String siv) {
// // 初始化解密数据
// bais = new ByteArrayInputStream(baos.toByteArray());
// // 声明解密输出
// baos = new ByteArrayOutputStream();
// // 解密
// encrypter.decrypt(bais,baos);
// //查看解密结果
// System.out.println(baos.toString("utf-8"));
return "";
}
public static void main(String args[]) {
try {
String sIV = "hellocxp";
String key = "15874498990";
String value = "96e63ae1-336b-4638-be20-5e2ac73bf2e3";
String outStr = encrypt(value, key, sIV);
// 结果
System.out.println(outStr);
} catch (Exception e) {
System.out.println("Exception e=" + e);
}
}
}