Conflicts:
	app/src/main/assets/omdb_config.json
	app/src/main/java/com/navinfo/omqs/ui/fragment/tasklist/TaskViewModel.kt
This commit is contained in:
qiji4215
2023-10-26 15:02:34 +08:00
24 changed files with 1465 additions and 835 deletions

View File

@@ -0,0 +1,27 @@
package com.navinfo.collect.library.data.entity
import android.os.Parcelable
import com.navinfo.collect.library.system.Constant
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt
import io.realm.RealmDictionary
import io.realm.RealmObject
import io.realm.RealmSet
import io.realm.annotations.Ignore
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import kotlinx.parcelize.Parcelize
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry
import org.oscim.core.MercatorProjection
import java.util.*
/**
* 渲染要素对应的实体
* */
@Parcelize
open class LinkRelation() : RealmObject(), Parcelable {
var linkPid:String = ""
var sNodeId: String? = null
var eNodeId: String? = null
}

View File

@@ -1,7 +1,11 @@
package com.navinfo.collect.library.data.entity
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt
import com.navinfo.collect.library.utils.StrZipUtil
import io.realm.RealmDictionary
import io.realm.RealmObject
import io.realm.RealmSet
@@ -14,18 +18,28 @@ import java.util.*
* 渲染要素对应的实体
* */
open class ReferenceEntity() : RealmObject() {
@PrimaryKey
var id: String = UUID.randomUUID().toString() // id
var renderEntityId: String = "" // 参考的renderEntity的Id
// @PrimaryKey
// var id: Int = 0 // id
// var renderEntityId: Int = 0 // 参考的renderEntity的Id
@Ignore
lateinit var name: String //要素名
lateinit var table: String //要素表名
var propertiesDb: String = ""
var code: String = "0" // 要素编码
@Ignore
var zoomMin: Int = 18 //显示最小级别
@Ignore
var zoomMax: Int = 23 //显示最大级别
var taskId: Int = 0 //任务ID
var enable:Int = 0 // 默认0不是显示 1为渲染显示
var geometry: String = "" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
var enable: Int = 0 // 默认0不是显示 1为渲染显示
var tileXMin: Int = 0
var tileXMax: Int = 0
var tileYMin: Int = 0
var tileYMax: Int = 0
var geometry: String =
"" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
get() {
wkt = GeometryTools.createGeometry(field)
return field
@@ -34,7 +48,13 @@ open class ReferenceEntity() : RealmObject() {
field = value
// 根据geometry自动计算当前要素的x-tile和y-tile
GeometryToolsKt.getTileXByGeometry(value, tileX)
tileXMin = tileX.min()
tileXMax = tileX.max()
GeometryToolsKt.getTileYByGeometry(value, tileY)
tileYMin = tileY.min()
tileYMax = tileY.max()
// 根据传入的geometry文本自动转换为Geometry对象
try {
wkt = GeometryTools.createGeometry(value)
@@ -55,11 +75,29 @@ open class ReferenceEntity() : RealmObject() {
}
return field
}
@Ignore
var properties: RealmDictionary<String> = RealmDictionary()
get() {
if (propertiesDb.isNotEmpty() && field.isEmpty()) {
try {
val gson = Gson()
val type = object : TypeToken<RealmDictionary<String>>() {}.type
field = gson.fromJson(StrZipUtil.uncompress(propertiesDb), type)
} catch (e: Exception) {
Log.e("jingo","ReferenceEntity 转 properties $e")
}
}
return field
}
@Ignore
var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码
@Ignore
var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码
constructor(name: String): this() {
constructor(name: String) : this() {
this.name = name
}
}

View File

@@ -1,40 +1,63 @@
package com.navinfo.collect.library.data.entity
import android.os.Parcelable
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.system.Constant
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt
import com.navinfo.collect.library.utils.StrZipUtil
import io.realm.RealmDictionary
import io.realm.RealmObject
import io.realm.RealmSet
import io.realm.annotations.Ignore
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import kotlinx.parcelize.Parcelize
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry
import org.oscim.core.MercatorProjection
import java.util.*
import java.util.zip.GZIPInputStream
/**
* 渲染要素对应的实体
* */
@Parcelize
open class RenderEntity() : RealmObject(), Parcelable {
@PrimaryKey
var id: String = UUID.randomUUID().toString() // id
// @PrimaryKey
// var id: String = UUID.randomUUID().toString() // id
lateinit var name: String //要素名
lateinit var table: String //要素表名
var code: String = "0" // 要素编码
var geometry: String = "" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
var propertiesDb: String = ""
var geometry: String =
"" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
get() {
wkt = GeometryTools.createGeometry(field)
return field
}
// get() {
// if (geometryDb != null && geometryDb.isNotEmpty() && field.isEmpty()) {
// field = StrZipUtil.uncompress(geometryDb)
// }
// return field
// }
set(value) {
field = value
// geometryDb = StrZipUtil.compress(value)
// 根据geometry自动计算当前要素的x-tile和y-tile
GeometryToolsKt.getTileXByGeometry(value, tileX)
tileXMin = tileX.min()
tileXMax = tileX.max()
GeometryToolsKt.getTileYByGeometry(value, tileY)
tileYMin = tileY.min()
tileYMax = tileY.max()
// 根据传入的geometry文本自动转换为Geometry对象
try {
wkt = GeometryTools.createGeometry(value)
@@ -50,36 +73,47 @@ open class RenderEntity() : RealmObject(), Parcelable {
try {
field = GeometryTools.createGeometry(geometry)
} catch (e: Exception) {
Log.e("jingo","RenderEntity 转 wkt失败 $e")
}
}
return field
}
@Ignore
var properties: RealmDictionary<String> = RealmDictionary()
get() {
if (propertiesDb != null && propertiesDb.isNotEmpty() && field.isEmpty()) {
try {
val gson = Gson()
val type = object : TypeToken<RealmDictionary<String>>() {}.type
field = gson.fromJson(StrZipUtil.uncompress(propertiesDb), type)
} catch (e: Exception) {
Log.e("jingo","RenderEntity 转 properties $e")
}
}
return field
}
@Ignore
var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码
@Ignore
var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码
var tileXMin: Int = 0
var tileXMax: Int = 0
var tileYMin: Int = 0
var tileYMax: Int = 0
var taskId: Int = 0 //任务ID
var zoomMin: Int = 18 //显示最小级别
var zoomMax: Int = 23 //显示最大级别
var enable:Int = 0 // 默认0不是显示 1为渲染显示 2为常显
var catchEnable:Int = 0 // 0不捕捉 1捕捉
var enable: Int = 0 // 默认0不是显示 1为渲染显示 2为常显
var catchEnable: Int = 0 // 0不捕捉 1捕捉
var linkPid: String = "" // RenderEntity关联的linkPid集合(可能会关联多个)
var linkRelation: LinkRelation? = null
constructor(name: String) : this() {
this.name = name
}
companion object {
object LinkTable {
//道路linkId
const val linkPid = "linkPid"
}
object LimitTable {
const val linkPid = "linkPid"
}
object KindCodeTable {
const val linkPid = "linkPid"
}
}
}

View File

@@ -224,7 +224,6 @@ private class MyLocationListener(callback: (BDLocation) -> Unit) : BDAbstractLoc
val call = callback;
override fun onReceiveLocation(location: BDLocation) {
call(location)
Log.e("jingo", "定位结果:速度=" + location.speed + " 方向=" + location.direction)
}
}

View File

@@ -6,6 +6,7 @@ import android.util.Log;
import androidx.annotation.RequiresApi;
import com.navinfo.collect.library.data.entity.ReferenceEntity;
import com.navinfo.collect.library.data.entity.RenderEntity;
import com.navinfo.collect.library.system.Constant;
import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.collect.library.utils.MapParamUtils;
@@ -17,6 +18,7 @@ import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@@ -41,14 +43,18 @@ public class OMDBReferenceDataSource implements ITileDataSource {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void query(MapTile tile, ITileDataSink mapDataSink) {
if(MapParamUtils.getTaskConfig() == null)
return;
// 获取tile对应的坐标范围
if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) {
Realm realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmQuery<ReferenceEntity> realmQuery = realm.where(ReferenceEntity.class);
int m = Constant.DATA_ZOOM - tile.zoomLevel;
int xStart = tile.tileX;
int xEnd = tile.tileX + 1;
int yStart = tile.tileY;
int yEnd = tile.tileY + 1;
if (m>0) {
if (m > 0) {
xStart = (int) (xStart << m);
xEnd = (int) (xEnd << m);
yStart = (int) (yStart << m);
@@ -56,21 +62,22 @@ public class OMDBReferenceDataSource implements ITileDataSource {
}
final int currentTileX = xStart;
if(isUpdate){
Realm.getInstance(MapParamUtils.getTaskConfig()).refresh();
if (isUpdate) {
realm.refresh();
isUpdate = false;
}
String sql = " tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + "";
String sql = " ((tileXMin <= " + xStart + " and tileXMax >= " + xStart + ") or (tileXMin <=" + xEnd + " and tileXMax >=" + xStart + ")) and ((tileYMin <= " + yStart + " and tileYMax >= " + yStart + ") or (tileYMin <=" + yEnd + " and tileYMin >=" + yStart + "))";
if(MapParamUtils.getDataLayerEnum()!=null){
// String sql = " tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + "";
if (MapParamUtils.getDataLayerEnum() != null) {
sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql();
}else{
} else {
sql += " and enable>=0";
}
RealmQuery<ReferenceEntity> realmQuery = Realm.getInstance(MapParamUtils.getTaskConfig()).where(ReferenceEntity.class)
.rawPredicate(sql);
realmQuery.rawPredicate(sql);
// 筛选不显示的数据
if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) {
realmQuery.beginGroup();
@@ -91,10 +98,11 @@ public class OMDBReferenceDataSource implements ITileDataSource {
} else {
mapDataSink.completed(QueryResult.SUCCESS);
}
Realm.getInstance(MapParamUtils.getTaskConfig()).close();
realm.close();
} else {
mapDataSink.completed(QueryResult.SUCCESS);
}
}
@Override
@@ -104,13 +112,12 @@ public class OMDBReferenceDataSource implements ITileDataSource {
@Override
public void cancel() {
if (Realm.getDefaultInstance().isInTransaction()) {
Realm.getDefaultInstance().cancelTransaction();
}
// if (Realm.getDefaultInstance().isInTransaction()) {
// Realm.getDefaultInstance().cancelTransaction();
// }
}
public void update(){
public void update() {
isUpdate = true;
Log.e("qj",Thread.currentThread().getName());
}
}

View File

@@ -11,21 +11,45 @@ import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.collect.library.utils.MapParamUtils;
import org.locationtech.jts.geom.Polygon;
import org.oscim.core.MapPosition;
import org.oscim.layers.tile.MapTile;
import org.oscim.map.Map;
import org.oscim.map.Viewport;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmQuery;
public class OMDBTileDataSource implements ITileDataSource {
class RealmObject {
int threadCode;
int realmConfigCode;
Realm realm;
}
// class DataObject {
// int threadCode = 0;
// byte zoom = 0;
// String lonLat = "";
// List<String> listIds = new ArrayList<>();
// }
private boolean isUpdate;
private Viewport viewport;
private List<RealmObject> realmObjectList = new ArrayList<>();
// private List<DataObject> dataObjectList = new ArrayList<>();
private final ThreadLocal<OMDBDataDecoder> mThreadLocalDecoders = new ThreadLocal<OMDBDataDecoder>() {
@Override
protected OMDBDataDecoder initialValue() {
@@ -40,36 +64,63 @@ public class OMDBTileDataSource implements ITileDataSource {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void query(MapTile tile, ITileDataSink mapDataSink) {
if(MapParamUtils.getTaskConfig() == null)
return;
// 获取tile对应的坐标范围
if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) {
Realm realm = null;
int threadCode = Thread.currentThread().hashCode();
synchronized (realmObjectList) {
int configCode = MapParamUtils.getTaskConfig().hashCode();
for (RealmObject object : realmObjectList) {
if (object.threadCode == threadCode) {
if (object.realmConfigCode == configCode) {
realm = object.realm;
} else {
object.realm.close();
realmObjectList.remove(object);
}
break;
}
}
if (realm == null) {
realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmObject o = new RealmObject();
o.threadCode = threadCode;
o.realmConfigCode = configCode;
o.realm = realm;
realmObjectList.add(o);
}
}
// Realm realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmQuery<RenderEntity> realmQuery = realm.where(RenderEntity.class);
int m = Constant.DATA_ZOOM - tile.zoomLevel;
int xStart = tile.tileX;
int xEnd = tile.tileX + 1;
int yStart = tile.tileY;
int yEnd = tile.tileY + 1;
if (m>0) {
if (m > 0) {
xStart = (int) (xStart << m);
xEnd = (int) (xEnd << m);
yStart = (int) (yStart << m);
yEnd = (int) (yEnd << m);
}
final int currentTileX = xStart;
if(isUpdate){
Realm.getInstance(MapParamUtils.getTaskConfig()).refresh();
if (isUpdate) {
realm.refresh();
isUpdate = false;
}
String sql =" tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + "";
if(MapParamUtils.getDataLayerEnum()!=null){
String sql = " ((tileXMin <= " + xStart + " and tileXMax >= " + xStart + ") or (tileXMin <=" + xEnd + " and tileXMax >=" + xStart + ")) and ((tileYMin <= " + yStart + " and tileYMax >= " + yStart + ") or (tileYMin <=" + yEnd + " and tileYMin >=" + yStart + "))";
if (MapParamUtils.getDataLayerEnum() != null) {
sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql();
}else{
} else {
sql += " and enable>=0";
}
realmQuery.rawPredicate(sql);
RealmQuery<RenderEntity> realmQuery = Realm.getInstance(MapParamUtils.getTaskConfig()).where(RenderEntity.class).rawPredicate(sql);
// 筛选不显示的数据
// 筛选不显示的数据
if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) {
realmQuery.beginGroup();
for (String type : Constant.HAD_LAYER_INVISIABLE_ARRAY) {
@@ -77,13 +128,17 @@ public class OMDBTileDataSource implements ITileDataSource {
}
realmQuery.endGroup();
}
List<RenderEntity> listResult = realmQuery/*.distinct("id")*/.findAll();
long time = System.currentTimeMillis();
List<RenderEntity> listResult = realmQuery.findAll();
long newTime = System.currentTimeMillis() - time;
Log.e("jingo", "当前OMDBTileDataSource " + Thread.currentThread().hashCode() + " 当前realm " + realm.hashCode() + " 查询耗时" + newTime + " 条数" + listResult.size());
// 数据记录的tile号是以正外接tile号列表此处过滤并未与当前tile相交的数据
if (!listResult.isEmpty()) {
Polygon tilePolygon = GeometryTools.getTilePolygon(tile);
// System.out.println("第一条数据的最小x值:" + listResult.get(0).getTileX().stream().min(Integer::compare).get());
// System.out.println("当前tile的:" + listResult.get(0).getTileX().stream().min(Integer::compare).get());
listResult = listResult.stream().filter((RenderEntity renderEntity) -> renderEntity.getWkt().intersects(tilePolygon))
listResult = listResult.stream().filter((RenderEntity renderEntity) ->
renderEntity.getWkt().intersects(tilePolygon)
)
/*过滤数据只有最小x屏幕的最小x或数据的最小x会被渲染跨Tile的其他数据不再重复渲染*/
// .filter((RenderEntity renderEntity) -> MercatorProjection.longitudeToTileX(viewport.fromScreenPoint(0,0).getLongitude(), (byte) Constant.DATA_ZOOM) == currentTileX || renderEntity.getTileX().stream().min(Integer::compare).get() == currentTileX)
.collect(Collectors.toList());
@@ -92,7 +147,7 @@ public class OMDBTileDataSource implements ITileDataSource {
} else {
mapDataSink.completed(QueryResult.SUCCESS);
}
Realm.getInstance(MapParamUtils.getTaskConfig()).close();
// realm.close();
} else {
mapDataSink.completed(QueryResult.SUCCESS);
}
@@ -105,13 +160,12 @@ public class OMDBTileDataSource implements ITileDataSource {
@Override
public void cancel() {
if (Realm.getDefaultInstance().isInTransaction()) {
Realm.getDefaultInstance().cancelTransaction();
}
// if (Realm.getDefaultInstance().isInTransaction()) {
// Realm.getDefaultInstance().cancelTransaction();
// }
}
public void update(){
public void update() {
isUpdate = true;
Log.e("qj",Thread.currentThread().getName());
}
}

View File

@@ -27,7 +27,7 @@ public class OMDBTileSource extends RealmDBTileSource {
@Override
public OpenResult open() {
Log.d("qj", Realm.getDefaultInstance().where(RenderEntity.class).findAll().size()+"open安装数量");
// Log.d("qj", Realm.getDefaultInstance().where(RenderEntity.class).findAll().size()+"open安装数量");
return OpenResult.SUCCESS;
}

View File

@@ -35,27 +35,29 @@ public class RealmDBTileDataSource implements ITileDataSource {
public void query(MapTile tile, ITileDataSink mapDataSink) {
// 获取tile对应的坐标范围
if (tile.zoomLevel>=15&&tile.zoomLevel<=Constant.OVER_ZOOM) {
int m = Constant.OVER_ZOOM-tile.zoomLevel;
int xStart = (int)tile.tileX<<m;
int xEnd = (int)((tile.tileX+1)<<m);
int yStart = (int)tile.tileY<<m;
int yEnd = (int)((tile.tileY+1)<<m);
RealmQuery<GeometryFeatureEntity> realmQuery = Realm.getDefaultInstance().where(GeometryFeatureEntity.class)
.rawPredicate("tileX>="+xStart+" and tileX<="+xEnd+" and tileY>="+yStart+" and tileY<="+yEnd);
// 筛选不显示的数据
if (Constant.HAD_LAYER_INVISIABLE_ARRAY!=null&&Constant.HAD_LAYER_INVISIABLE_ARRAY.length>0) {
realmQuery.beginGroup();
for (String type: Constant.HAD_LAYER_INVISIABLE_ARRAY) {
realmQuery.notEqualTo("name", type);
}
realmQuery.endGroup();
}
List<GeometryFeatureEntity> listResult = realmQuery.distinct("id").findAll();
mThreadLocalDecoders.get().decode(tile, mapDataSink, listResult);
mapDataSink.completed(QueryResult.SUCCESS);
Realm.getDefaultInstance().close();
Log.e("jingo","RealmDBTileDataSource RealmDBTileDataSource RealmDBTileDataSource");
// int m = Constant.OVER_ZOOM-tile.zoomLevel;
// int xStart = (int)tile.tileX<<m;
// int xEnd = (int)((tile.tileX+1)<<m);
// int yStart = (int)tile.tileY<<m;
// int yEnd = (int)((tile.tileY+1)<<m);
//
// RealmQuery<GeometryFeatureEntity> realmQuery = Realm.getDefaultInstance().where(GeometryFeatureEntity.class)
// .rawPredicate("tileX>="+xStart+" and tileX<="+xEnd+" and tileY>="+yStart+" and tileY<="+yEnd);
// // 筛选不显示的数据
// if (Constant.HAD_LAYER_INVISIABLE_ARRAY!=null&&Constant.HAD_LAYER_INVISIABLE_ARRAY.length>0) {
// realmQuery.beginGroup();
// for (String type: Constant.HAD_LAYER_INVISIABLE_ARRAY) {
// realmQuery.notEqualTo("name", type);
// }
// realmQuery.endGroup();
// }
// List<GeometryFeatureEntity> listResult = realmQuery.distinct("id").findAll();
// mThreadLocalDecoders.get().decode(tile, mapDataSink, listResult);
// mapDataSink.completed(QueryResult.SUCCESS);
// Realm.getDefaultInstance().close();
// Log.d("RealmDBTileDataSource", "tile:"+tile.getBoundingBox().toString());
mapDataSink.completed(QueryResult.SUCCESS);
} else {
mapDataSink.completed(QueryResult.SUCCESS);
}
@@ -68,8 +70,8 @@ public class RealmDBTileDataSource implements ITileDataSource {
@Override
public void cancel() {
if (Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).isInTransaction()) {
Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).cancelTransaction();
}
// if (Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).isInTransaction()) {
// Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).cancelTransaction();
// }
}
}

View File

@@ -0,0 +1,282 @@
package com.navinfo.collect.library.utils
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
import java.util.zip.*
object StrZipUtil {
/**
* @param input 需要压缩的字符串
* @return 压缩后的字符串
* @throws IOException IO
*/
fun compress(input: String): String {
if (input.isEmpty()) {
return input
}
try {
val out = ByteArrayOutputStream()
val gzipOs = GZIPOutputStream(out)
gzipOs.write(input.toByteArray())
gzipOs.close()
return BASE64Encoder().encode(out.toByteArray())
} catch (e: Exception) {
return input
}
}
/**
* @param zippedStr 压缩后的字符串
* @return 解压缩后的
* @throws IOException IO
*/
fun uncompress(zippedStr: String): String {
if (zippedStr.isEmpty()) {
return zippedStr
}
try {
val out = ByteArrayOutputStream()
val `in` = ByteArrayInputStream(
BASE64Decoder().decodeBuffer(zippedStr)
)
val gzipIs = GZIPInputStream(`in`)
val buffer = ByteArray(256)
var n: Int
while (gzipIs.read(buffer).also { n = it } >= 0) {
out.write(buffer, 0, n)
}
// toString()使用平台默认编码也可以显式的指定如toString("GBK")
return out.toString()
} catch (e: Exception) {
return zippedStr
}
}
/***
* 压缩GZip
*
* @param data
* @return
*/
fun gZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bos = ByteArrayOutputStream()
val gzip = GZIPOutputStream(bos)
gzip.write(data)
gzip.finish()
gzip.close()
b = bos.toByteArray()
bos.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 解压GZip
*
* @param data
* @return
*/
fun unGZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bis = ByteArrayInputStream(data)
val gzip = GZIPInputStream(bis)
val buf = ByteArray(1024)
var num = -1
val baos = ByteArrayOutputStream()
while (gzip.read(buf, 0, buf.size).also { num = it } != -1) {
baos.write(buf, 0, num)
}
b = baos.toByteArray()
baos.flush()
baos.close()
gzip.close()
bis.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 压缩Zip
*
* @param data
* @return
*/
fun zip(data: ByteArray): ByteArray? {
var b: ByteArray? = null
try {
val bos = ByteArrayOutputStream()
val zip = ZipOutputStream(bos)
val entry = ZipEntry("zip")
entry.size = data.size.toLong()
zip.putNextEntry(entry)
zip.write(data)
zip.closeEntry()
zip.close()
b = bos.toByteArray()
bos.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 解压Zip
*
* @param data
* @return
*/
fun unZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bis = ByteArrayInputStream(data)
val zip = ZipInputStream(bis)
while (zip.nextEntry != null) {
val buf = ByteArray(1024)
var num = -1
val baos = ByteArrayOutputStream()
while (zip.read(buf, 0, buf.size).also { num = it } != -1) {
baos.write(buf, 0, num)
}
b = baos.toByteArray()
baos.flush()
baos.close()
}
zip.close()
bis.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
// /***
// * 压缩BZip2
// *
// * @param data
// * @return
// */
// public static byte[] bZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CBZip2OutputStream bzip2 = new CBZip2OutputStream(bos);
// bzip2.write(data);
// bzip2.flush();
// bzip2.close();
// b = bos.toByteArray();
// bos.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 解压BZip2
// *
// * @param data
// * @return
// */
// public static byte[] unBZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// CBZip2InputStream bzip2 = new CBZip2InputStream(bis);
// byte[] buf = new byte[1024];
// int num = -1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// while ((num = bzip2.read(buf, 0, buf.length)) != -1) {
// baos.write(buf, 0, num);
// }
// b = baos.toByteArray();
// baos.flush();
// baos.close();
// bzip2.close();
// bis.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 压缩BZip2
// *
// * @param data
// * @return
// */
// public static byte[] bZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CBZip2OutputStream bzip2 = new CBZip2OutputStream(bos);
// bzip2.write(data);
// bzip2.flush();
// bzip2.close();
// b = bos.toByteArray();
// bos.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 解压BZip2
// *
// * @param data
// * @return
// */
// public static byte[] unBZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// CBZip2InputStream bzip2 = new CBZip2InputStream(bis);
// byte[] buf = new byte[1024];
// int num = -1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// while ((num = bzip2.read(buf, 0, buf.length)) != -1) {
// baos.write(buf, 0, num);
// }
// b = baos.toByteArray();
// baos.flush();
// baos.close();
// bzip2.close();
// bis.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
/**
* 把字节数组转换成16进制字符串
*
* @param bArray
* @return
*/
fun bytesToHexString(bArray: ByteArray): String? {
val sb = StringBuffer(bArray.size)
var sTemp: String
for (i in bArray.indices) {
sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
if (sTemp.length < 2) sb.append(0)
sb.append(sTemp.uppercase(Locale.getDefault()))
}
return sb.toString()
}
}