package com.xxxxxx.xfast.js.lib;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.rms.*;
import com.xxxxxx.xdsc.js.Binding;
import com.xxxxxx.xdsc.js.Library;
import com.xxxxxx.xdsc.js.Variable;
import com.xxxxxx.Manager.view.canvas.MyCanvas;
import com.xxxxxx.Manager.model.json.EngineClientFile;
import com.xxxxxx.Manager.model.json.EngineResponse;
import com.xxxxxx.xfast.js.core.ArrayObject;
import com.xxxxxx.xfast.json.JSONArray;
import com.xxxxxx.xfast.json.JSONException;
import com.xxxxxx.xfast.json.JSONObject;
public class JsFile implements Binding, RecordFilter{
private long downloadVTS;
private String source;
private String dirInServer;
private String serverDownloadDir = MyCanvas.baseUrl + "/EngineService/"+ this.dirInServer + "/";
private String serverUrl = MyCanvas.baseUrl + "/EngineService/service";
private String clientSyncDir = "file:///root1/" + MyCanvas.userId + "Sync/";
private String upServerUrl = MyCanvas.baseUrl + "/EngineService/sync"; // 上传访问servlet
private static final int TRY_NUM = 2; // 上传下载文件出错时可重传的次数限制
private static final int SLEEP = 2000; // 线程睡眠时间
public boolean getProperty(Object thisObj, int id, String name,
Variable result) {
return false;
}
public boolean setProperty(Object obj, int id, String name, Variable value) {
return false;
}
public boolean callFunction(Object thisObj, int id, String name,
Variable result, Variable args) {
if (name.equals("upload")){
if(upload(args.getStr(0),args.getStr(1)))
result.setValue(true);
else
result.setValue(false);
}
else if (name.equals("download")){
if(download((ArrayObject)args.getObj(0,ArrayObject.class)))
result.setValue(true);
else
result.setValue(false);
}
else if (name.equals("getDownloadList"))
result.setValue(getDownloadList());
else if (name.equals("getShareList"))
result.setValue(getShareList(args.getStr(0)));
else if (name.equals("syncDownload")){
if(syncDownload((ArrayObject)args.getObj(0,ArrayObject.class)))
result.setValue(true);
else
result.setValue(false);
}
else if (name.equals("getRoots"))
result.setValue(getRoots());
else if (name.equals("getFiles"))
result.setValue(getFiles(args.getStr(0)));
else if (name.equals("init")){
// 检查syncRS
boolean okRS = checkSyncRS();
// 检查Dir
if (okRS) {
boolean okDir = checkDir(MyCanvas.userId);
if (okDir)
{
long vts = getVts(MyCanvas.userId);
System.out.println("vts:"+vts);
}
else
System.out.println("Error:check dir,record.");
}
}
else if (name.equals("initRS"))
initRS(args.getStr(0));
else
return false;
boolean okRS = checkSyncRS();
// 检查Dir
if (okRS) {
boolean okDir = checkDir(MyCanvas.userId);
if (okDir) {
long vts = getVts(MyCanvas.userId);
System.out.println("vts:" + vts);
} else
System.out.println("Error:check dir,record.");
}
return true;
}
public ArrayObject split(String obj, String dot) {
ArrayObject arrayObject = new ArrayObject();
int stringLength = obj.length();
int count = 0;
int startIndex = obj.indexOf(dot);
String name = obj.substring(0, startIndex);
// 取名称
arrayObject.put(count++, name);
arrayObject.length++;
String type = obj.substring(startIndex+1, stringLength);
// 取类型
arrayObject.put(count++, type);
arrayObject.length++;
return arrayObject;
}
//获取所有根目录
private ArrayObject getRoots()
{
ArrayObject roots = new ArrayObject();
Vector rootsList = new Vector();
Enumeration enumRoot = FileSystemRegistry.listRoots();//返回根目录组成的序列
while(enumRoot.hasMoreElements())
{
String rt = new String((String)enumRoot.nextElement());
rootsList.addElement(rt);
System.out.println(rootsList.toString());
for(int i=0; i<rootsList.size(); i++){
roots.put(i, rootsList.elementAt(i).toString());
}
}
return roots;
}
/*得到root下所有文件绝对路径。root 格式:root/ */
private ArrayObject getFiles(String root){
String basePath = "file:///"+root;
Vector files = new Vector();
ArrayObject aoFiles = new ArrayObject();
//得到basePath下所有文件绝对路径
getFilesPath(basePath,files);
System.out.println(files.size()+" files:"+files.toString());
for(int i=0; i<files.size(); i++){
aoFiles.put(i, files.elementAt(i).toString());
}
return aoFiles;
}
private void getFilesPath(String currPath,Vector files)
{
// 递归输出 basePath 下所有文件
/*
* 1. 循环扫描当前路径下所有文件夹及文件
* 2. 是文件,就添加进vector
* 3. 是文件夹,更新当前路径,递归进入扫描
*/
try
{
FileConnection fc = (FileConnection) Connector.open(currPath);//创建对应的连接对象
if(!fc.isDirectory()){
files.addElement(currPath);
fc.close();
}
else{
Enumeration enumFolders = fc.list();//调用list函数获取文件夹内容序列
fc.close();
while(enumFolders.hasMoreElements())//遍历序列并将内容添加到列表中
{
String listInfo = (String)enumFolders.nextElement();
if(listInfo.charAt(listInfo.length()-1) == '/'){ //文件夹
getFilesPath(currPath+listInfo,files);
}
else{ // 是文件
files.addElement(currPath+listInfo);
}
}
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
public ArrayObject getDownloadList() {
ArrayObject downlist = new ArrayObject();
long vts = getVts(MyCanvas.userId);
if (vts == -1) {
System.out.println("Error: get vts.download canceled.");
} else if (vts == -2) {
System.out.println("Error: no vts.download canceled.");
} else {
// 发送JSON
EngineClientFile ecfs = new EngineClientFile(serverUrl,
MyCanvas.sessionId, "huaweiWidget");
ecfs.setSync_type("fileSyncDownload");
ecfs.setFileSyncDownload("versionTS", vts);
ecfs.setSynReq(true);
// 接收JSON
EngineResponse resp = null;
try {
resp = ecfs.getResponse();
if (resp.getResult().equals("1000")) { // 异常
System.out.println("Error: responsed JSON.result:1000");
return null;
}
//设置一些必要的变量
this.downloadVTS = resp.getJSONBody().getJSONObject("fileSyncDownload").getLong("versionTS");
if(this.downloadVTS > vts){
this.dirInServer = MyCanvas.userId;
this.serverDownloadDir = MyCanvas.baseUrl + "/EngineService/"+ this.dirInServer + "/";
JSONArray content = resp.getJSONBody().getJSONObject("fileSyncDownload").getJSONArray("content");
for(int i=0; i < content.length(); i++){
downlist.put(i,content.get(i).toString());
}
return downlist;
}
else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public ArrayObject getShareList(String sourceUserID){
ArrayObject downlist = new ArrayObject();
long vts = getVts(MyCanvas.userId);
if (vts == -1) {
System.out.println("Error: get vts.download canceled.");
} else if (vts == -2) {
System.out.println("Error: no vts.download canceled.");
} else {
//发送JSON
EngineClientFile ecfs = new EngineClientFile(serverUrl,MyCanvas.sessionId, "huaweiWidget");
ecfs.setSync_type("fileShare");
ecfs.setFileShare("source", sourceUserID);
ecfs.setSynReq(true);
// 接收JSON
EngineResponse resp = null;
try {
resp = ecfs.getResponse();
if (resp.getResult().equals("1000")) { // 异常
System.out.println("Error: responsed JSON.result:1000");
return null;
}
//设置一些必要的变量
this.dirInServer = sourceUserID;
this.serverDownloadDir = MyCanvas.baseUrl + "/EngineService/"+ this.dirInServer + "/";
JSONArray content = resp.getJSONBody().getJSONObject("fileShare").getJSONArray("content");
for(int i=0; i < content.length(); i++){
downlist.put(i,content.get(i).toString());
}
return downlist;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public boolean download(ArrayObject downlist) {
SyncFile[] files = null;
if (null != downlist) {
// 取得name[],type[].....
int length = downlist.length;
files = new SyncFile[length];
System.out.println("share resource from:" + this.dirInServer + ":");
for (int i = 0; i < length; i++) {
files[i] = new SyncFile();
String fileNameType = new String(downlist.get(i).toString());
System.out.println("file:" + fileNameType);
ArrayObject nameType = new ArrayObject();
nameType = split(fileNameType, ".");
files[i].setFileName(nameType.get(0).toString()); // 取名称
files[i].setFileType(nameType.get(1).toString()); // 取类型
System.out.println(files[i].getFileName() + "."
+ files[i].getFileType() + ", "
);
}
boolean okDf = false;
for (int i = 0; i < length; i++) {
int tryNum = TRY_NUM;
while (tryNum-- > 0) {
// 下载文件
okDf = downloadFile(this.serverDownloadDir, clientSyncDir,
files[i].getFileName(), files[i].getFileType());
if (!okDf) { // 下载失败,等待2秒重试
try {
System.out.println("download file:"
+ files[i].getFileName() + "."
+ files[i].getFileType()
+ " failed,try again...");
Thread.sleep(SLEEP);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
} else { // 下载成功
return true;
}
}
tryNum = TRY_NUM;
}
} else {
System.out.println("Error: no download files!");
return false;
}
return false;
}
public boolean syncDownload(ArrayObject downlist){
System.out.println(downlist.toString());
// 下载时的文件数组
SyncFile[] files = null;
String[] filesName = null; // 存需下载的文件
String[] filesType = null;
String[] okFilesName = null; // 存下载成功的文件
String[] okFilesType = null;
boolean fileNull = true; // 标志filesName的null与否
long vts = getVts(MyCanvas.userId);
if (vts >= this.downloadVTS) {
System.out.println("Error: local vts equals to rspVts. Download canceled.");
return false;
} else {
// 取得name[],type[].....
files = new SyncFile[downlist.length];
int length = downlist.length;
for (int i = 0; i < length; i++) {
files[i] = new SyncFile();
try {
JSONObject contentObject = new JSONObject(downlist.get(i)
.toString());
files[i].setFileName(contentObject.getString("name"));
files[i].setFileType(contentObject.getString("type"));
files[i].setFileSize(contentObject.getLong("size"));
files[i].setFileDesc(contentObject.getString("description"));
System.out.println(files[i].getFileName() + "."
+ files[i].getFileType() + ", "
+ files[i].getFileSize() + ", "
+ files[i].getFileDesc());
} catch (JSONException je) {
je.printStackTrace();
return false;
}
}
// 发送下载文件请求,下载文件
okFilesName = new String[length];
okFilesType = new String[length];
// /////////////////////// 打印所有JSON里文件信息
System.out.println("resp vts:" + this.downloadVTS);
System.out.println("resp files:");
for(int i=0;i<length;i++){
System.out.println(files[i].getFileName()+"."+files[i].getFileType());
}
/////////////////////////
/*
* 检查userID的RS里需要下载哪些文件:只下载RS里没有而filesName[]里有的文件;
* 若RS里已包含所有的filesName[]里的文件,则删除该RS。
*/
// 取userID的RS里所有的文件记录
DownloadObj[] rcs = getRCs(MyCanvas.userId);
int rcsNum = 0;
if(null != rcs){
rcsNum = rcs.length;
}
if ( rcsNum == 0) { // userID的RS里无记录,需下载所有文件
System.out.println("no rc in RS:"+MyCanvas.userId+",to download all files...");
filesName = new String[length];
filesType = new String[length];
for (int k = 0; k < length; k++) {
filesName[k] = new String(files[k].getFileName());
filesType[k] = new String(files[k].getFileType());
}
int okNum = downloadFiles(MyCanvas.userId, filesName, filesType,
okFilesName, okFilesType, TRY_NUM);
if (okNum == length) { // 所有的文件下载成功
int id = getId(MyCanvas.userId);
if (id != 0) { // 只需更改记录
if (setRc(id, MyCanvas.userId, this.downloadVTS)) {
System.out.println("set rc succeed.");
// 删除userID 的 RMS
try {
RecordStore.deleteRecordStore(MyCanvas.userId);
System.out.println("delete RS:" + MyCanvas.userId);
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
} else {
System.out.println("Error: set rc.");
return false;
}
} else {
System.out.println("Error: no rc."); // //
return false;
}
} else {
System.out
.println("Warning: download "
+ (length - okNum) + " files failed.");
// 在该userID的RMS里记录已下载的文件名称和类型
boolean okAdd = addDownloadRCs(MyCanvas.userId, okFilesName,
okFilesType, okNum);
if (!okAdd) { // 失败,原因有:打开RS、序列化、不是所有文件信息存储成功
return false;// //// $$$$$$$$$$$$
} else
return true; // 成功,无操作
}
} else { // 比较userID的RS里记录与json返回的文件
filesName = new String[length-rcsNum];
filesType = new String[length-rcsNum];
Hashtable rcsHash = new Hashtable();
// 建立Hashtable映射
for (int i = 0; i < rcsNum; i++) {
rcsHash.put(rcs[i].getFileName() + "."
+ rcs[i].getFileType(), rcs[i].getFileName()
+ "." + rcs[i].getFileType());
}
// 遍历jsonFilesName[],找出rcs里没有的文件(2集合不一定是包含关系!!!)
int j = 0;
String jsonFile = null;
System.out.println("comparing jsonFiles and RS...");
for (int i = 0; i < length; i++) {
jsonFile = new String(files[i].getFileName() + "."
+ files[i].getFileType());
if (jsonFile.equals(rcsHash.get(jsonFile))) { // 在RS里找到
System.out.println("both of JSON and RS have:" + jsonFile);
}
else { // RS里没有
System.out.println("RS has no:" + jsonFile);
filesName[j] = new String(files[i].getFileName());
filesType[j++] = new String(files[i].getFileType());
fileNull = false;
}
}
/* 若有,则下载;否则,无操作 */
if (fileNull) { // 无需下载
System.out.println("Warning: all files had been downloaded before.download canceled.");
// 删除userID的RS
try {
RecordStore.deleteRecordStore(MyCanvas.userId);
System.out.println("ok: delete RS:" + MyCanvas.userId);
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
// 更新vts
int id = getId(MyCanvas.userId); // 该userID记录必定已存在,使用set更新记录
if (setRc(id, MyCanvas.userId, this.downloadVTS))
System.out.println("ok: set rc.");
else
System.out.println("Error: set rc."); // 重试setRC()
// ????
} else { // 需要下载
int okNum = downloadFiles(MyCanvas.userId, filesName, filesType, okFilesName,okFilesType,TRY_NUM);
if(okNum == (length-rcsNum)){ // 所有的文件下载成功
int id = getId(MyCanvas.userId);
if (id != 0) { // 只需更改记录
if (setRc(id, MyCanvas.userId, this.downloadVTS)){
System.out.println("ok: set rc.");
// 删除userID de RMS
try {
RecordStore.deleteRecordStore(MyCanvas.userId);
System.out.println("ok: delete RS:" + MyCanvas.userId);
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
}
else{
System.out.println("Error: set rc.");
return false;
}
}
else{
System.out.println("Error: no rc,impossible error.");
return false;/////
}
}
else{
System.out.println("Warning: download "
+ (length-rcsNum - okNum) + " files failed.");
// 在该userID的RMS里记录已下载的文件名称和类型
boolean okAdd = addDownloadRCs(MyCanvas.userId,okFilesName,okFilesType,okNum);
if (!okAdd) { // 失败,原因有:打开RS、序列化、不是所有文件信息存储成功
return false;// //// $$$$$$$$$$$$
} else
return true; // 成功,无操作
}
}
}
}
return false;
}
public boolean upload(String uploadfile,String filePath) {
JSONObject jsonBody;
try {
jsonBody = new JSONObject(
"{/"sync_type/":/"fileSyncUpload/",/"fileSyncUpload/":{/"content/":["
+ uploadfile + "]}}");
// 取得jsonBody里的文件信息
SyncFile file = new SyncFile();
JSONObject contentObject = new JSONObject();
contentObject = jsonBody.getJSONObject("fileSyncUpload")
.getJSONArray("content").getJSONObject(0);
long size = 0;
int tryNum = TRY_NUM;
// 上传文件
while (tryNum-- > 0) {
// 上传文件(取得文件大小)
System.out.println("!!!!!!!!!!!!!!"+filePath);
size = uploadFile(upServerUrl, filePath);
file.setFileName(contentObject.optString("name"));
file.setFileType(contentObject.optString("type"));
file.setFileSize(size);
file.setFileAccs(contentObject.optString("accessibility"));
file.setFileDesc(contentObject.optString("description"));
if (0 == size) // 重传文件,允许重传tryNum次
{
try {
System.out.println("upload failed,try again...");
Thread.sleep(SLEEP);
} catch (Exception ex) {
ex.printStackTrace();
}
} else { // 上传成功
break;
}
}
// 上传JSON
if (0 != size) {
size = 0;
long respVts = upSyncJSON(file);
if (respVts != 0) { // 表返回的VTS没有出错
// 得到syncRS里的记录
int id = getId(MyCanvas.userId);
if (id != 0) { // 已存在记录,只需更改记录
if (setRc(id, MyCanvas.userId, respVts)) {
System.out.println("ok: set rc.");
} else {
System.out.println("Error: set rc");
return false;
}// 重试setRC() ????
} else { // 无记录,需增加记录
if (addRc(MyCanvas.userId, respVts)) {
System.out.println("ok: set rc.");
} else {
System.out.println("Error: set rc.");
return false;
} // 重试setRC() ????
}
} else { // 返回的VTS出错
System.out.println("Error: resp JSON.");
return false;
}
}
} catch (JSONException je) {
je.printStackTrace();
return false;
}
return true;
}
private long uploadFile(String upServerUrl, String filePath) {
FileConnection fc = null;
long fileSize = 0;
// 读取本地文件
try {
byte[] data = null;
if (System.getProperty("microedition.io.file.FileConnection.version") != null) {
try {
fc = (FileConnection) Connector.open(filePath,Connector.READ_WRITE);
if(!fc.exists()){
System.out.println("Error: file:"+filePath+" not exists.");
return 0;
}
fileSize = fc.fileSize(); //
InputStream in = fc.openInputStream();
fc.close();
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
byte[] tmp = new byte[4096];
int n;
while ((n = in.read(tmp)) != -1) {
out.write(tmp, 0, n);
out.flush();
}
in.close();
out.close();
data = out.toByteArray();
} catch (IOException ioe) {
ioe.printStackTrace();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
else{
System.out.println("Error: device do not support file operation.");
return 0;
}
//上传文件
HttpConnection conn = (HttpConnection) Connector.open(upServerUrl,Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("sync-type", "fileSyncUpload");
conn.setRequestProperty("user-id", MyCanvas.userId);
OutputStream output = conn.openOutputStream();
output.write(data);
//output.flush();
output.close();
//接收服务器端返回的code,200表上传成功
if (conn.getResponseCode() == 200) {
return fileSize;
} else {
System.out.println("Error: HttpConnection.Code=" + conn.getResponseCode());
return 0;
}
} catch (IOException ioe) {
ioe.printStackTrace();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// 上传多个文件
/* private int uploadFiles(String upServerUrl, SyncFile[] files, SyncFile[] okFiles, SyncFile[] noFiles,int filesNum,int tryNum) {
int okNum = 0;
int noNum = 0;
boolean okUf = false;
for (int i = 0; i < filesNum; i++) {
while (tryNum-- > 0) {
// 上传文件(取得文件大小)
okUf = uploadFile(upServerUrl, files[i]); //notice!!!原版函数
if (!okUf) // 重传文件,允许重传tryNum次
{
try {
System.out
.println("upload failed,try again...");
Thread.sleep(SLEEP);
} catch (Exception ex) {
ex.printStackTrace();
}
}
else{ //上传成功
okFiles[okNum]= new SyncFile();
okFiles[okNum++] = files[i]; // 拷贝
break;
}
}
// 上传失败
if (tryNum <= 0) {
noFiles[noNum]= new SyncFile();
noFiles[noNum++] = files[i]; // 拷贝
}
tryNum = TRY_NUM;
}
return okNum; //等于filesNum表示全部上传成功
}
*/
// 初始化RS里的userID 的记录,并删除userID的RS
private boolean initRS(String userID) {
RecordStore rs = null;
RObject ro = new RObject();
RecordEnumeration re = null;
byte[] data =null;
String rcUserID = new String();
int id = 0; //
try {
rs = RecordStore.openRecordStore("syncRS", true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
data = re.nextRecord();
try {
ro = byteArray2Object(data);
data = null;
} catch (Exception ex) {
System.out.println("Error:byteArray2Object");
rs.closeRecordStore();
ex.printStackTrace();
return false;
}
rcUserID = ro.getUserID();
if (userID.equals(rcUserID)) { // UserID有记录
id = ro.getID(); // 取原ID,一定大于0
if(setRc(id, userID, 0)){ //初始化记录,vts置0
System.out.println("ok: init record in syncRS.");
}
break;
}
rcUserID = null;
}
rs.closeRecordStore();
} catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return false;
} catch (RecordStoreFullException rsfe) {
rsfe.printStackTrace();
return false;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
// 检查Dir
boolean okRS = checkSyncRS();
if (okRS) {
boolean okDir = checkDir(MyCanvas.userId);
if (okDir)
{
System.out.println("ok: check dir.");
getVts(MyCanvas.userId);
}
else{
System.out.println("Error: check dir.");
}
}
// 删除userIDd的RS,如果存在的话
try{
String[] RS = RecordStore.listRecordStores();
int rsNum = RS.length;
int i = 0;
for (i = 0; i < rsNum; i++) {
if (RS[i].equals(userID)) { // 存在userID 的RS
RecordStore.deleteRecordStore(userID);
System.out.println("ok: delete RS:"+userID);
break;
}
}
}catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return true;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
System.out.println("ok: init syncRS,delete RS:"+userID);
return true;
}
// 检查Dir
private boolean checkDir(String userID) {
// 根据Dir的状态检查syncRS的记录
int cd = hasDir(userID);
if (cd == 0) { // 文件夹已存在,检查记录
int id = getId(userID);
if (id == 0) { // 无原记录,必须用addrecord()初始化
if (addRc(userID, 0)){
System.out.println("ok: add record.");
}
else{
System.out.println("Error:add record.");
return false;
}
}
else ; //有原记录,无操作
} // end of if(cd ==0)
else if (cd == 1){ // 创建了文件夹,并检查syncRS里的记录
int id = getId(userID);
if (id == 0) { // 无原记录,必须用addrecord()初始化
if (addRc(userID, 0)){
System.out.println("add record succeed./n");
}
else {
System.out.println("Error:add record./n");
return false;
}
}
else { // 有原记录ID,用setrecord()初始化
if (setRc(id, userID, 0)){
System.out.println("set record succeed.id="+id+"/n");
}
else {
System.out.println("Error:set record./n");
return false;
}
}
System.out.println("create dir:" + clientSyncDir);
}
else if (cd == -1) { // 出错
return false;
}
System.out.println("ok: check dir");
return true;
}
public boolean newInstance(int id, String name, Variable result,Variable args) {
return false;
}
// 检查syncRS
private boolean checkSyncRS() {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore("syncRS", true);
System.out.println("ok: check RS: syncRS.");
} catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return false;
} catch (RecordStoreFullException rsfe) {
rsfe.printStackTrace();
return false;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
} finally {
try {
rs.closeRecordStore();
} catch (RecordStoreException rse) {
rse.printStackTrace();
}
}
return true;
}
// 检查Dir是否存在
private int hasDir(String userID) {
FileConnection fc = null;
try {
fc = (FileConnection)(Connector.open(clientSyncDir,Connector.READ_WRITE));
// 文件夹不存在(可能是用户删除了,但不保证syncRS里记录没有;或是从没创建过。),新建Dir。
if (!fc.isDirectory()) {
fc.mkdir();
fc.close();
return 1; //表新建文件夹
}
else{
System.out.println("dir:" + clientSyncDir + " already exists.");
}
fc.close();
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("Error:open dir.");
return -1; // 表出错
}
return 0; // 表已存在
}
// 得到syncRS里的userID 的ID号
private int getId(String userID) {
RObject ro = new RObject();
RecordStore rs = null;
RecordEnumeration re = null;
byte[] data = null;
String rcUserID = new String();
int id = 0; //
try {
rs = RecordStore.openRecordStore("syncRS", false);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
data = re.nextRecord();
try {
ro = byteArray2Object(data);
data = null;
} catch (Exception ex) {
System.out.println("Error: byteArray2Object.");
rs.closeRecordStore();
ex.printStackTrace();
return -1;
}
rcUserID = ro.getUserID();
if (userID.equals(rcUserID)) { // UserID有记录
id = ro.getID(); // 取原ID,一定大于0
break;
}
rcUserID = null;
}
rs.closeRecordStore();
} catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return -1;
} catch (RecordStoreFullException rsfe) {
rsfe.printStackTrace();
return -1;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return -1;
}
return id;
}
// 向syncRS里增加记录
private boolean addRc(String userID, long vts) {
RecordStore rs = null;
int id = 0;
try {
rs = RecordStore.openRecordStore("syncRS", false);
id = rs.getNextRecordID(); // 得到下一条ID的值
rs.closeRecordStore();
} catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return false;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
byte[] objByteArray = rsObject2bytes(id, userID, vts, clientSyncDir);
boolean okBRS = false;
okBRS = byteArraytoRS(userID,id, objByteArray, true); // 增加该ID的记录(true)
return okBRS;
}
// 更改syncRS里的记录
private boolean setRc(int id, String userID, long vts) {
byte[] objByteArray = rsObject2bytes(id, userID, vts, clientSyncDir);
boolean okBRS = byteArraytoRS(userID,id, objByteArray, false); // 更改该ID的记录(false)
return okBRS;
}
// 同步文件类
class SyncFile {
String fileName = null;
String fileType = null;
long fileSize;
String fileAccs = null;
String fileDesc = null;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileAccs() {
return fileAccs;
}
public void setFileAccs(String fileAccs) {
this.fileAccs = fileAccs;
}
public String getFileDesc() {
return fileDesc;
}
public void setFileDesc(String fileDesc) {
this.fileDesc = fileDesc;
}
}
// 上行同步JSON
public long upSyncJSON(SyncFile file) {
long respVts = 0;
JSONArray ContArray = new JSONArray();
JSONObject contObject = new JSONObject();
// 生成JSON消息体
try {
contObject.put("name", file.getFileName());
contObject.put("type", file.getFileType());
contObject.put("size", file.getFileSize());
contObject.put("accessibility", file.getFileAccs());
contObject.put("description", file.getFileDesc());
System.out.println("name:"+file.getFileName());
ContArray.put(contObject);
} catch (JSONException je) {
je.printStackTrace();
return 0;
}
// 发送JSON
EngineClientFile ecfs = new EngineClientFile(serverUrl,MyCanvas.sessionId, "huaweiWidget");
ecfs.setSync_type("fileSyncUpload");
ecfs.setFileSyncUpload("content", ContArray);
ecfs.setSynReq(true);
JSONObject jsonBody = new JSONObject();
JSONObject fileSyncUploadObject = new JSONObject();
// 接收JSON
try {
EngineResponse resp = ecfs.getResponse();
if(resp.getResult().equals("1000")){ // 返回异常
System.out.println("Error: responsed shareJSON.result:1000");
return 0;
}
jsonBody = resp.getJSONBody();
fileSyncUploadObject = jsonBody.getJSONObject("fileSyncUpload");
//返回的vts
respVts = fileSyncUploadObject.getLong("versionTS");
System.out.println("resp vts=" + respVts);
} catch (Exception e) {
System.out.println("Error: resp JSON.");
e.printStackTrace();
return 0;
}
return respVts;
}
// 下载所有文件
private int downloadFiles(String userID,String[] filesName,String[] filesType,String[] okFilesName,String[] okFilesType,int tryNum){
System.out.println("downloading file...");
int num = filesName.length;
int t = 0; //记录tmpFilesName及tmpFilesType中对象个数
boolean okDf = false;
for (int i = 0; i < num; i++) {
while (tryNum-- > 0) {
okDf = downloadFile(this.serverDownloadDir,clientSyncDir,filesName[i],filesType[i]);
if (!okDf) { // 下载失败,等待2秒重试
try {
System.out.println("download file:"+filesName[i]+"."+filesType[i]+" failed,try again...");
Thread.sleep(SLEEP);
} catch (Exception ex) {
ex.printStackTrace();
}
}
else { // 下载成功,记录文件名,类型
okFilesName[t] = filesName[i];
okFilesType[t++] = filesType[i];
break;
}
} // while
if (tryNum == 0) {
System.out.println("Error: " + TRY_NUM + " try failed.");
}
tryNum = TRY_NUM;
} // for()
return t;
}
// 增加下行同步时已下载文件的记录
private boolean addDownloadRCs(String userID,String[] filesName,String[] filesType,int num){
boolean okRs = false;
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(userID, true);
okRs = true;
} catch (RecordStoreNotFoundException rsnf) {
rsnf.printStackTrace();
return false;
} catch (RecordStoreFullException rsfe) {
rsfe.printStackTrace();
return false;
} catch (RecordStoreException rse) {
rse.printStackTrace();
return false;
}
if (okRs) {
// 存入文件记录
int okNum = 0;
byte[] data = null;
DownloadObj dobj = new DownloadObj();
while (okNum < num) {
// 创建记录对象,序列化
dobj.setFileName(filesName[okNum]);
dobj.setFileType(filesType[okNum]);
try {
data = dobj.serialize();
} catch (Exception ex) {
System.out.println("Error: serialize");
ex.printStackTrace();
return false;
}
// 序列化字节数组存入userID的RS
try {
rs.addRecord(data, 0, data.length);
} catch (RecordStoreFullException rsfe) {
System.out.println("Warning: RS:" + userID + " is full.");
/*
* 1个RS大约可用空间100K=102400B,假设每条记录(ID+name+type)
* 约为20B,可存5120条记录。 足够!!不考虑另建RS $$$$$$$$$$$$$$$$$
*/
rsfe.printStackTrace();
} catch (RecordStoreException rse) {
rse.printStackTrace();
}
okNum++;
data = null;
} // while
if (okNum == num) {
System.out.println("record all downloaded files.");
} else {
System.out.println("Error: record downloaded files.");
return false;
}
try {
rs.closeRecordStore();
} catch (Reco