My favorites | Sign in
Project Logo
                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
/*
* Application.java
*/

package com.imity;

import com.exploringxml.xml.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;

import javax.microedition.io.*;
import java.io.*;
import java.util.*;
import de.enough.polish.util.*;
//import javax.wireless.messaging.MessageConnection;
//import javax.wireless.messaging.MessageListener;

import javax.microedition.midlet.MIDletStateChangeException;
import de.enough.polish.util.Locale;
import de.enough.polish.ui.*;

//import de.enough.polish.blackberry.ui.*;

//#ifdef polish.debugEnabled
import de.enough.polish.util.Debug;
//#endif


/**
*
* @author shim
*/

public class Application {

private Application() {
AccountNumber = 0;
}

public static Application getInstance() {
if (_instance == null) {
_instance = new Application();
_instance.initialize();
}
return _instance;
}

public String DebugStr = "";

// Shared UUID by server and client
public static final UUID RFCOMM_UUID = new UUID(0x0003);
public static final UUID IMITY_UUID = new UUID("3000010008000000805F9B34FB49D4EE",false);
public String localAddress = "";
public static int MaxDiscoveries = 2;
public Hashtable Discoveries;
public ImityObjects Bookmarks;
public ImityObjects WorldObjects;
public ImityObjects LocalObjects;
public ImityObjects Notifications;
public Hashtable FriendDevices;
public Hashtable PersonDevices;
public boolean isDemo = false;

public ObexService obexService = null;

public ImityLogger Logger;

private int scanWaitTime = 1000;
private Person LocalPerson = null;


//#ifdef config.ConnectToLocalhost:defined

private static String ServerUrl = "http://emulator.imity.com:3000/api/spp";
public static String ServerDomainName = "emulator.imity.com";
private static String LoginUrl = "http://emulator.imity.com:3000/api/login";

//#else

private static String ServerUrl = "http://my.imity.com/api/spp";
public static String ServerDomainName = "my.imity.com";
private static String LoginUrl = "http://my.imity.com/api/login";

//#endif

public ImityMidlet SPM;

public static final int firstChildOccur[] = {1};

public static final String RECORDSTORE_SPP = "sp_spp";
public static final String RECORDSTORE_LOCALOBJECTS = "sp_local";
public static final String RECORDSTORE_ACCOUNT = "sp_account";
public static final String RECORDSTORE_NOTICES = "sp_notices";
public static final String RECORDSTORE_NOTICE_OBJECTS = "sp_notice_objects";
public static final String RECORDSTORE_BYTE_COUNT = "sp_byte_count";
public static final long timeDiffRecent = 1000 * 40; //40 sec
public static final long timeDiffLong = 1000 * 60 * 2; //2 min
public static final int AUTOUPLOAD_INTERVAL_MINS = 5;

private static Application _instance;
private int AccountNumber;

public boolean serviceSearchRunning = false;
public boolean submittingData = false;
public boolean scanning = false;
public long nextAutoUpload = 0;

public String Encoding = "";
public String SessionId = "";
public String State = "1";
public long bytes_this_session = 0;
public long bytes_since_login = 0;

private void initialize() {

submittingData = false;
nextAutoUpload = System.currentTimeMillis() + (1000 * 60 * Application.AUTOUPLOAD_INTERVAL_MINS);


try {

Bookmarks = new ImityObjects();
Discoveries = new Hashtable();
WorldObjects = new ImityObjects();
LocalObjects = new ImityObjects();
Notifications = new ImityObjects();
FriendDevices = new Hashtable();
PersonDevices = new Hashtable();
Logger = ImityLogger.getInstance();


localAddress = LocalDevice.getLocalDevice().getBluetoothAddress();
Logger.imityStart();
if (LocalDevice.getLocalDevice().getDiscoverable() != DiscoveryAgent.GIAC) {
LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
}

//load local objects
//


Hashtable lor = RecordStoreUtil.readData(Application.RECORDSTORE_ACCOUNT);

String acc_string = "";
for (Enumeration e = lor.elements(); e.hasMoreElements();) {
acc_string = (String)e.nextElement();
}

try {
String[] AccData = TextUtil.split(acc_string,';');
AccountNumber = Integer.parseInt(AccData[0]);
SessionId = AccData[1];
} catch (Exception ex) {
}


lor = RecordStoreUtil.readData(Application.RECORDSTORE_LOCALOBJECTS);

for (Enumeration e = lor.elements(); e.hasMoreElements();) {
try {
String rsStr = "<lo>" + (String)e.nextElement() + "</lo>";
//appendString("-rs-str:" + rsStr);
ImityObjects io = Application.DeSerializeLocalData(rsStr);

for (Enumeration e2 = io.elements(); e2.hasMoreElements();) {
SpimeObject spo = (SpimeObject)e2.nextElement();
if (spo.getClassId() > 0) {
LocalObjects.put(spo.getId(),spo);
//appendString("-lo-d-:" + spo.getId() + " ");
}

}

} catch (Exception ex) {
appendString("DeSerialization exception while processing local objects recordstore:" + ex);
}

}


lor = RecordStoreUtil.readData(Application.RECORDSTORE_NOTICE_OBJECTS);

for (Enumeration e = lor.elements(); e.hasMoreElements();) {
try {
String rsStr = "<lo>" + (String)e.nextElement() + "</lo>";
//appendString("-rs-str:" + rsStr);
ImityObjects io = Application.DeSerializeLocalData(rsStr);

for (Enumeration e2 = io.elements(); e2.hasMoreElements();) {
SpimeObject spo = (SpimeObject)e2.nextElement();
if (spo.getClassId() > 0) {
WorldObjects.put(spo.getId(),spo);
appendString("-put-local-notice-obj-into-worl-:" + spo.getId() + " ");
}

}

} catch (Exception ex) {
appendString("DeSerialization exception while processing notice objects recordstore:" + ex);
}

}

refreshFriendDevices();

Hashtable nos = RecordStoreUtil.readData(Application.RECORDSTORE_NOTICES);

for (Enumeration e = nos.elements(); e.hasMoreElements();) {
String rsStr = "<nos>" + (String)e.nextElement() + "</nos>";
try {
//appendString("-rs-str:" + rsStr);
ImityObjects io = Application.DeSerializeNotifications(rsStr);

for (Enumeration e2 = io.elements(); e2.hasMoreElements();) {
Notice no = (Notice)e2.nextElement();
if (no != null) {
Notifications.put(no.getId(),no);
appendString("-notice-on-:" + no.NoticeSpid + " ");
}
}

} catch (Exception ex) {
appendString("DS-ex-NOS");
}
}

String bytes_as_string = RecordStoreUtil.readString(Application.RECORDSTORE_BYTE_COUNT);
if (bytes_as_string != null) {
bytes_since_login = Long.parseLong(bytes_as_string);
}


//obexService = new ObexService(this);
//obexService.startService();
}
catch (Exception ex) {
appendString("Exception: " + ex.toString() + ":" + ex.getMessage());
}

}

public void shutDown() {
obexService.shutDown();
//obexService.stopService();
}

public void startScanJob() {

startScanJob(null);
}

public void forceScanJob(ImityMidlet spm) {
if (SPM == null) SPM = spm;

Timer timer = new Timer();
timer.schedule(new ForcedScanDevicesTask(this,spm),10);

}

public void startScanJob(ImityMidlet spm) {

if (SPM == null) SPM = spm;

Timer timer = new Timer();
timer.schedule(new ScanDevicesTask(this,spm),scanWaitTime);

if ((scanWaitTime == 6000) && (SPM != null)) SPM.autoSubmitData();


if (scanWaitTime < 30000) scanWaitTime += 5000;
//appendString("-s-ds-");
}



public void scanForDevices() {
scanForDevices(false);
}
public void scanForDevices(boolean isForced) {
ImityDiscoveryListener spdl = new ImityDiscoveryListener(this);
spdl.isForced = isForced;
}


public void scanForDevices(ImityMidlet spm) {
scanForDevices(spm, false);
}

public void scanForDevices(ImityMidlet spm,boolean isForced) {
ImityDiscoveryListener spdl = new ImityDiscoveryListener(this, spm);
spdl.isForced = isForced;
}

public Bookmark bookmark() {

/* test */
/*
this.addDeviceInfo(new BluetoothDevice("MAC1","TEST NAME 1"));
this.addDeviceInfo(new BluetoothDevice("MAC2","TEST NAME 2"));

((BluetoothDevice)(Devices.get("MAC1"))).ImityServiceUrl = "proto://MAC1/1234";
((BluetoothDevice)(Devices.get("MAC2"))).ImityServiceUrl = "proto://MAC2/1234";
*/
/* test end */


Bookmark bm = new Bookmark(WorldObjects);

return bm;
//Bookmarks.put(bm.Tag,bm);

}


public void appendString(String str) {
//SET TO TRUE
appendString(str, true);
}

public void appendString(String str, boolean ignore) {
if (!ignore) {
DebugStr += str;

if (null != SPM) {
Form df = SPM.get_DebugForm();
}
}
}

public void clearAllRecords() {
RecordStoreUtil.clearData(Application.RECORDSTORE_SPP);
}

public final static String readData(StreamConnection conn) {

InputStream input = null;
byte[] data = null;

try {
input = conn.openInputStream();

// Probably want to throw an exception if length is not greater then 0
int length = input.read();
data= new byte[length];
length = 0;

// Assemble data
while (length != data.length) {
int ch = input.read(data, length, data.length - length);
if (ch == -1) {
throw new IOException("Can't read data");
}
length += ch;
}

} catch (IOException e) {
System.err.println(e);
} finally {

// close input stream
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
return new String(data);
}

void addDeviceInfo(BluetoothDevice bd) {

addDeviceInfo(bd, null);
}

void addDeviceInfo(BluetoothDevice bd, ImityMidlet spm) {

boolean changes = false;

//Check that bd is phone or computer
if ((bd.getMajorClass() != 256 && bd.getMajorClass() != 512)) {
//
//Check that bd is phone
//if (bd.getMajorClass() != 512) {
return;
}

try {

if (WorldObjects.containsKey(bd.getId())) {


BluetoothDevice bdd = (BluetoothDevice)WorldObjects.get(bd.getId());

//appendString("-R-" + bd.BluetoothAddress + "\r\n");
if (bdd.FriendlyName.equals("") && !bd.FriendlyName.equals("")) {
bdd.FriendlyName = bd.FriendlyName;
bdd.setLogged(false);
changes = true;
}

if (bdd.getMajorClass() == 0 && bd.getMajorClass() > 0) {
bdd.setMajorClass(bd.getMajorClass());
}
if (bdd.getMinorClass() == 0 && bd.getMinorClass() > 0) {
bdd.setMinorClass(bd.getMajorClass());
}

bdd.setDiscoveryDate(bd.getDiscoveryDate());

if (!bdd.inProximity())
{
bdd.setInProximity(true);
Logger.bluetoothDeviceArrive(bdd.getId());
}



//Devices.remove(bd.BluetoothAddress);
//appendString("-r-" + bd.BluetoothAddress + "\r\n");
} else
{

WorldObjects.put(bd.getId(),bd);
bd.setInProximity(true);
Logger.bluetoothDeviceArrive(bd.getId());

//appendString("-ToWorld-" + bd.BluetoothAddress + "\r\n");
if (null != spm) {

SpimeChoiceItem dvli;

if (bd.isFriend()) {

/* } else
if (bd.hasUnreadMessages()) {
//#style messageListItem
dvli = new SpimeChoiceItem(bd.getId(),bd.FriendlyName,null,Choice.IMPLICIT);
dvli.addCommand(spm.get_showMessages());

spm.ObjectList.add(dvli);
} else if (bd.hasImityService()) {
//#style shoutpodListItem
dvli = new SpimeChoiceItem(bd.getId(),bd.FriendlyName,null,Choice.IMPLICIT);
dvli.addCommand(spm.get_showMessages());

spm.ObjectList.add(dvli); */
} else {
if (bd.inProximity() && !bd.getDisplayName().equals("")) {
//#style deviceListItemUpdating
dvli = new SpimeChoiceItem(bd.getId(),bd.getDisplayName(),null,Choice.IMPLICIT);
spm.ObjectList.add(dvli);
}
}

}

}

if ((null != spm) && (changes)) spm.refreshObjectList();

} catch (Exception ex) {
appendString("AddDeviceInfo Exception: " + ex.toString() + ":" + ex.getMessage());
}

}

public void deleteDataRecordStores() {
try {
RecordStoreUtil.clearData(Application.RECORDSTORE_SPP);
RecordStoreUtil.clearData(Application.RECORDSTORE_LOCALOBJECTS);
RecordStoreUtil.clearData(Application.RECORDSTORE_ACCOUNT);
RecordStoreUtil.clearData(Application.RECORDSTORE_NOTICES);
RecordStoreUtil.clearData(Application.RECORDSTORE_NOTICE_OBJECTS);
} catch (Exception ex) {}
}

public void saveNotifications() {

try {
String nos = Notifications.toImityElementsString(true,-1);

RecordStoreUtil.clearData(Application.RECORDSTORE_NOTICES);
RecordStoreUtil.clearData(Application.RECORDSTORE_NOTICE_OBJECTS);
if (nos != null) {
RecordStoreUtil.writeData(Application.RECORDSTORE_NOTICES, nos);
}

String n_objects = "";
for (Enumeration e = Notifications.elements(); e.hasMoreElements();) {
Notice n = (Notice)e.nextElement();
try {
SpimeObject spo = (SpimeObject)WorldObjects.get(n.NoticeSpid);

if (spo != null) {
n_objects += spo.toXmlElementString();
//appendString("putting object:" + spo.getId() + " into notice cache");
}


} catch (Exception ex) {}
}

//appendString("notice_objects_cache:" + n_objects);

if (!n_objects.equals("")) {

RecordStoreUtil.writeData(Application.RECORDSTORE_NOTICE_OBJECTS, n_objects);
}

} catch (Exception ex) {
appendString("-nos-saveDataException: " + ex);
}

}

public void saveDataToRecordStore() {

try {

saveNotifications();
String spp = makeImityElements(false);
String lspp = LocalObjects.toImityElementsString(true, -1);

if (spp != null) {
RecordStoreUtil.writeData(Application.RECORDSTORE_SPP, spp);
}

RecordStoreUtil.clearData(Application.RECORDSTORE_LOCALOBJECTS);
if (lspp != null) {
RecordStoreUtil.writeData(Application.RECORDSTORE_LOCALOBJECTS, lspp);
}
RecordStoreUtil.clearData(Application.RECORDSTORE_BYTE_COUNT);
if (bytes_since_login != 0) {
RecordStoreUtil.writeString(Application.RECORDSTORE_BYTE_COUNT, Long.toString(bytes_since_login));
}


} catch (Exception ex) {
appendString("saveDataException: " + ex);
}

}

public String makeImityDataPackage() {
String contents = "";

String elementStr = makeImityElements();

if (elementStr != null) contents += elementStr;

/*
Hashtable h = RecordStoreUtil.readData(Application.RECORDSTORE_SPP);
for (Enumeration e = h.elements(); e.hasMoreElements();) {
contents += (String)e.nextElement();
}
*/


return makeImityPackage(contents);

}

public String makeImityPackage(String contents) {
String imityPackage = null;
try {

long localTime = System.currentTimeMillis();
String transactionId = generateUid();
imityPackage = "<spp sessid=\"" + SessionId + "\" state=\"" + State + "\" cltrid=\"" + transactionId + "\" aid=\"" + getAccountId() + "\" lt=\"" + localTime + "\" a=\"" + localDeviceId() + "\">";

imityPackage += contents;

imityPackage += "</spp>";

String testString = "<spp sessid=\"" + SessionId + "\" state=\"" + State + "\" cltrid=\"" + transactionId + "\" aid=\"" + getAccountId() + "\" lt=\"" + localTime + "\" a=\"" + localDeviceId() + "\">";
testString += "";
testString += "</spp>";

if (imityPackage.equals(testString)) {
return null;
}

} catch (Exception ex) {
appendString("-make-spp-exception-: " + ex);
}

return "<?xml version=\"1.0\" encoding=\"" + Application.getInstance().Encoding + "\"?>\n" + imityPackage;

}

public String makeImityElements(boolean includeLocalObjects) {
String shoutpodElements = "";
try {
ImityObjects spo = WorldObjects.clone();
shoutpodElements += Bookmarks.toImityElementsString();
if (includeLocalObjects) shoutpodElements += LocalObjects.toImityElementsString();
shoutpodElements += Logger.toString();
shoutpodElements += spo.toImityElementsString(false,4); //ignore person spime
} catch (Exception ex) {
appendString("-make-spp-e-exception-:" + ex);
}

if (shoutpodElements.equals("")) return null;
return shoutpodElements;

}

public String makeImityElements() {
return makeImityElements(true);
}

/*
public void submitDataToFile() {

long cTime = System.currentTimeMillis();
String imityPackage = makeImityDataPackage();

String ret = "";

if (imityPackage != null) {
//There is data to send

//Special build that dumps a file instead of uploading
//ret = HttpUtil.HttpPostPackage(this.ServerUrl,HttpUtil.URLencode(imityPackage));

FileUtil fu = new FileUtil();

fu.saveTextFile(imityPackage);

ret = "0";

// Should do some updates to world here if info is received from services.
} else {
//Show no data to send alert
ret = "-102:No data to send";
}


if (ret.equals("0")) {
//Update logged flag on devices
Logger.deleteEntriesBefore(cTime);
Bookmarks.setAllLogged();
WorldObjects.setAllLogged();
LocalObjects.setAllLogged();

RecordStoreUtil.clearData(Application.RECORDSTORE_SPP);
}

appendString("Submit returned:" + ret + "\r\n");

}
*/

public void submitDataToServer() {
submitDataToServer("",true);
}

public void submitDataToServer(String dataPackage,boolean retryOnFail) {

long cTime = System.currentTimeMillis();


String imityPackage = dataPackage;

if (imityPackage.equals("")) imityPackage = makeImityDataPackage();
//appendString("-before sending:" + imityPackage);

String ret = "";

if (imityPackage != null) {
//There is data to send
//appendString("-pdata:" + imityPackage + "-");
ret = HttpUtil.HttpPostPackage(this.ServerUrl,HttpUtil.URLencode(imityPackage));
//appendString("-rdata:" + ret + "-");
// Should do some updates to world here if info is received from services.
} else {
//Show no data to send alert
ret = "<spp a=\"local\" c=\"800\"/>";
}

int retCode = 800;

Hashtable retData = processServerSpp(ret);

if (retData.containsKey("returnCode")) retCode = Integer.parseInt((String)retData.get("returnCode"));


if (retCode == 200) {
//Update logged flag on devices

Logger.deleteEntriesBefore(cTime);
Bookmarks.setAllLogged();
WorldObjects.setAllLogged();
LocalObjects.setAllLogged();

RecordStoreUtil.clearData(Application.RECORDSTORE_SPP);

State = "1";

} else if (retCode == 401) {
if (SPM != null) {
SPM.alertAndLogout("Invalid Session","Your session id is no longer valid. You will have to logout.");
}
} else if (retryOnFail) {
try {

appendString("Submit returned:(" + retCode + "). Retry in 5s");
Thread.sleep(5000);

appendString("-Retrying-");
submitDataToServer(imityPackage,false);
} catch (Exception ex) {}
return;

}



appendString("Submit returned:(" + retCode + ")");

if (retCode == 800) {
appendString("ret:" + ret);
State = "0";
}

/* if (!scanning) forceScanJob(SPM); */
}

public int sendSpimeObject(String RecipientSpid, SpimeObject so) {
try {

ObexClient oc = new ObexClient(this);

String btaddr_to_send_to = "";
String recipient_spid = "";
if (WorldObjects.containsKey(RecipientSpid)) {
Person p = (Person)WorldObjects.get(RecipientSpid);
if (!p.isNear()) return -1;
btaddr_to_send_to = p.isNearAddress;
recipient_spid = p.getId();
}

if (LocalObjects.containsKey(RecipientSpid)) {
Friend f = (Friend)LocalObjects.get(RecipientSpid);
if (!f.isNear()) return -1;
btaddr_to_send_to = f.isNearAddress;
recipient_spid = f.PersonRef;
}

if (so.getClassId() == 3) {

//This is a message
Message m = (Message)so;
m.ReceiverPersonSpid = recipient_spid;
m.SenderPersonSpid = getLocalPerson().getId();
BluetoothDevice btd = new BluetoothDevice(localAddress,"",0,0);

}

BluetoothDevice btd = new BluetoothDevice(btaddr_to_send_to,"",0,0);

if (WorldObjects.containsKey(btd.getId())) {
oc.sendSpimeObject((BluetoothDevice)WorldObjects.get(btd.getId()),so);
}
} catch (Exception ex) {
appendString("sendSpimeObject Exception: " + ex + "\r\n");
return -1;
}

return 0;
}

public void notifyNewObject(String soid) {

try {
SpimeObject so = (SpimeObject)WorldObjects.get(soid);

/* If we are running in a midlet lets act */
if (null != SPM) {
SPM.NotifyNewObject();
}

} catch (Exception ex) {
}

}


public void notifyObjectNotSent(BluetoothDevice btdToSendTo, SpimeObject spoToSend) {
if (null != SPM) {
/*
if (spoToSend.getClassId() == 3) {
try {

if (SPM.activeSoid == btdToSendTo.getId()) {
SPM.AddErrorMessageToMessageForm(btdToSendTo.getDisplayName(), ((Message)spoToSend).Text);
} else {
//Should at error to the shout messages dialog once I have it in place
}

} catch (Exception ex) {
appendString("Could not append new message to MessageForm");
}
}
*/

SPM.autoSubmitData();
}
}

public static ImityObjects DeSerializeNotifications(String xmlStr) {

ImityObjects io = new ImityObjects();

try {
Node root = new Xparse().parse(xmlStr);
Node lo = root.find("nos", firstChildOccur);
if (lo == null) return io;

for (int x = 0; x < lo.contents.length(); x++) {
try {
int occur[] = {(x + 1)};
Node nextNode = lo.find("no", occur);

if (nextNode != null) {
Notice n = Notice.DeSerialize(nextNode);
io.put(n.getId(),n);
}

} catch (Exception ex) {

Application.getInstance().appendString("-a-DS-nos-ex:" + ex);

}

}


} catch (Exception ex) { }

return io;


}

public static ImityObjects DeSerializeLocalData(String xmlStr) {

//Application.getInstance().appendString("parse:" + xmlStr);
ImityObjects io = new ImityObjects();

try {
Node root = new Xparse().parse(xmlStr);
Node lo = root.find("lo", firstChildOccur);
if (lo == null) return io;

for (int x = 0; x < lo.contents.length(); x++) {
try {
int occur[] = {(x + 1)};
Node nextNode = lo.find("o", occur);
String classId = "" + nextNode.attributes.get("classId");

if (classId.equals("5")) {
Friend f = Friend.DeSerialize(nextNode);
io.put(f.getId(),f);
}
if (classId.equals("4")) {
//Application.getInstance().appendString("We got a person");
Person p = Person.DeSerialize(nextNode);
io.put(p.getId(),p);

//Application.getInstance().appendString("person deserialized");
}
if (classId.equals("1")) {
BluetoothDevice b = BluetoothDevice.DeSerialize(nextNode);
io.put(b.getId(),b);
}

} catch (Exception ex) {

Application.getInstance().appendString("-a-DS-lo-ex:" + ex);

}

}


} catch (Exception ex) { }

return io;

}

public static SpimeObject DeSerializeSpimeData(String xmlStr) {

try {
Node root = new Xparse().parse(xmlStr);
Node o = root.find("o", firstChildOccur);
if (o == null) return null;

int classId = Integer.parseInt((String)o.attributes.get("classId"));

if (classId == 1) return BluetoothDevice.DeSerialize(o);
if (classId == 3) return Message.DeSerialize(o);
if (classId == 5) return Friend.DeSerialize(o);

} catch (Exception ex) { }

return null;
}

public void LogWorldObjects() {

/* Should create log entries for upload in recordstore or upload directly if there is a
* proxy service available?
*
* Also update objects that have not been discovered for a while. Eg a bluetooth devices not
* discovered within 60 sec should not have a ImityServiceUrl etc.
* */

// loop though world objects

//appendString("-lwo-");
boolean changes = false;

Hashtable objectsToRemove = new Hashtable();

try {

for (Enumeration e = WorldObjects.elements() ; e.hasMoreElements() ;) {

SpimeObject so = (SpimeObject)e.nextElement();

if (so.getClassId() == 1) {
BluetoothDevice btd = (BluetoothDevice)so;

if (btd.inProximity()) {

if (((btd.getDiscoveryDate() + timeDiffRecent) < System.currentTimeMillis()) && (btd.hasImityService())) {
//appendString("Resetting SPUrl on: " + btd.getId());
btd.ImityServiceUrl = "";
changes = true;
}
if ((btd.getDiscoveryDate() + timeDiffLong) < System.currentTimeMillis() ) {
//appendString("Removing btd: " + btd.getId());
//objectsToRemove.put(btd.getId(),btd.getId());

btd.setInProximity(false);

Logger.bluetoothDeviceLeave(btd.getId());
changes = true;
}

}

}
}
/*
for (Enumeration e = objectsToRemove.elements(); e.hasMoreElements() ;) {
String cKey = (String)e.nextElement();

WorldObjects.remove(cKey);
}
*/


} catch (Exception ex) {
appendString("LogWorld Exception: " + ex);
}

/*
Bookmark bm = bookmark();
Bookmarks.put(bm.getId(),bm);
*/

if (changes && SPM != null) {

//appendString("-lwo-refresh-");
SPM.refreshObjectList();
}


}


public String login(String login, String pwd) {

if (login.equals("debug")) {
AccountNumber = 666;

RecordStoreUtil.clearData(Application.RECORDSTORE_ACCOUNT);
RecordStoreUtil.writeData(Application.RECORDSTORE_ACCOUNT,"" + AccountNumber + ";DEBUGSESSION");
bytes_since_login = 0;
RecordStoreUtil.clearData(Application.RECORDSTORE_BYTE_COUNT);
RecordStoreUtil.writeString(Application.RECORDSTORE_BYTE_COUNT, Long.toString(bytes_since_login));



return null;
}

/* send account package to login url and parse response*/

String contents = "<login><l><![CDATA[" + login + "]]></l><p><![CDATA[" + pwd + "]]></p></login>";
String imityPackage = makeImityPackage(contents);


String ret = "";

if (imityPackage != null) {
//There is data to send

ret = HttpUtil.HttpPostPackage(Application.LoginUrl,HttpUtil.URLencode(imityPackage));

// Should do some updates to world here if info is received from services.
} else {
//Show no data to send alert
ret = "-102:No data to send";
return ret;
}

//appendString("login ret raw:" + ret + "\r\n");

int retCode = -1;
int accountNumber = -1;


Hashtable retData = processServerSpp(ret);

if (retData.containsKey("returnCode")) retCode = Integer.parseInt((String)retData.get("returnCode"));
if (retData.containsKey("accountNumber")) accountNumber = Integer.parseInt((String)retData.get("accountNumber"));
if (retData.containsKey("sessionId")) SessionId = (String)retData.get("sessionId");

//appendString("login returned:" + retCode + "\r\n");
if (retCode == 200 && accountNumber > 0) {
//set accountId and person and create/update recordstore Application.RECORDSTORE_ACCOUNT

RecordStoreUtil.clearData(Application.RECORDSTORE_ACCOUNT);
RecordStoreUtil.writeData(Application.RECORDSTORE_ACCOUNT,"" + accountNumber + ";" + SessionId);
bytes_since_login = 0;
saveDataToRecordStore();

return null;
} else if (retCode == 203) {
return "Bad username or password";
} else if (!retData.containsKey("returnCode")) {
return "Could not connect to server";
}
AccountNumber = -1;
return "There was a problem logging in. Please try again";
}

public Hashtable processServerSpp(String sppStr) {
Hashtable retData = new Hashtable();

/* parsing response from server*/
try {
//appendString("-startparse-");
Node root = new Xparse().parse(sppStr);


//appendString("-spp-parse-:" + sppStr);
Node spp = root.find("spp", firstChildOccur);
if (spp != null) {

//appendString("-c-attrib-");
retData.put("returnCode",(String)spp.attributes.get("c"));

//appendString("-account-node-");
Node account = spp.find("account", firstChildOccur);
if (account != null) {
//appendString("-number-attrib-");
retData.put("accountNumber", (String)account.attributes.get("number"));

AccountNumber = Integer.parseInt((String)retData.get("accountNumber"));
}

try {
String sessionId = (String)spp.attributes.get("sessid");
retData.put("sessionId",sessionId);
} catch (Exception ex) {

}

Node spoNode = spp.find("spo", firstChildOccur);

if (spoNode != null) {

for (int x = 0; x < spoNode.contents.length(); x++) {
try {
int occur[] = {(x + 1)};
Node nextNode = spoNode.find("o", occur);
String classId = "" + nextNode.attributes.get("classId");

String isDead = "0";
try {
isDead = "" + nextNode.attributes.get("d");
} catch (Exception ex) {
appendString("-is-dead-ex:" + ex);
}

if (classId.equals("4")) {
Person person = Person.DeSerialize(nextNode);

person.setLastUpdated(System.currentTimeMillis());
if (person.UID.equals("" + AccountNumber))
{
LocalObjects.put(person.getId(),person);
} else {

//appendString("-ds-p-add:" + person.toXmlElementString() + "-");
//Check for Local Friends who should be updated

Friend f = findFriendByPersonRef(person.getId());

if (f != null) {
f.setLastUpdated(System.currentTimeMillis());
f.Name.setValue(person.Name);
f.FriendName.setValue(person.Name);
f.Weblog.setValue(person.Weblog);
f.Tagline.setValue(person.Tagline);
f.About.setValue(person.About);
f.ImageUrl.setValue(person.ImageUrl);
f.Devices = person.Devices.clone();
f.Journal.setValue(person.Journal);
//f.setPublicTags(person.getPublicTagString());
//f.setPublicNotes(person.getPublicNotes().clone());

}

WorldObjects.put(person.getId(),person);

if (isDead.equals("1")) {
appendString("remove person " + person.getId());
WorldObjects.remove(person.getId());
}

}

}
if (classId.equals("5")) {
Friend friend = Friend.DeSerialize(nextNode);
friend.setLastUpdated(System.currentTimeMillis());
LocalObjects.put(friend.getId(),friend);

if (isDead.equals("1")) {
appendString("remove friend " + friend.getId());
WorldObjects.remove(friend.getId());
}

}
if (classId.equals("1")) {
BluetoothDevice btd = BluetoothDevice.DeSerialize(nextNode);

if (WorldObjects.containsKey(btd.getId())) {

BluetoothDevice btdWorld = (BluetoothDevice)WorldObjects.get(btd.getId());
btdWorld.setLastUpdated(System.currentTimeMillis());
btdWorld.Journal.setValue(btd.Journal);
btdWorld.setPublicTags(btd.getPublicTagString());
btdWorld.setPublicNotes(btd.getPublicNotes().clone());
btdWorld.PublicName = btd.PublicName;
btdWorld.PublicNameWhen = btd.PublicNameWhen;
btdWorld.PublicNameWho = btd.PublicNameWho;


}

/* I dont do dead bit checks on devices since they should never be dead
* and since the only time they are cached are if one has setup notices on them */
}

} catch (Exception ex) {

Application.getInstance().appendString("-spo-l-DS-d-ex:" + ex);

}

}

}

//notices

for (int x = 0; x < spp.contents.length(); x++) {
try {
int occur[] = {(x + 1)};
Node nextNode = spp.find("no", occur);
if (nextNode != null) {
Notice no = Notice.DeSerialize(nextNode);
Notifications.put(no.getId(),no);
}
} catch (Exception ex) {
Application.getInstance().appendString("-nos-l-DS-d-ex:" + ex);
}
}

} else {
//appendString("-no-spp-element-");
}

} catch (Exception ex) {
appendString("-login-response-exception:" + ex);
return new Hashtable();
}

refreshFriendDevices();

saveNotifications();
Logger.checkForNotices();


if (null != SPM) {
SPM.notifyUpdates();
}
return retData;
}


public boolean hasAccountId() {
// TODO: Deal with pre signup accounts....
if (AccountNumber > 0) return true;
return false;
}

public String getAccountId() {
if (AccountNumber > 0) return "" + AccountNumber;
return null;
}

public void refreshFriendDevices() {
/*name should be changed to profileStatusUpdate of something similar*/


FriendDevices.clear();
PersonDevices.clear();

for (Enumeration e = LocalObjects.elements(); e.hasMoreElements();) {
try {
SpimeObject spo = (SpimeObject)e.nextElement();

if (spo.getClassId() == 5) {
Friend f = (Friend)spo;
try {
BluetoothDevice btd = new BluetoothDevice(f.FirstAddr.toString(), "", 1, 1);
//appendString("-fd-p:" + btd.getId() + "-" + f.getId());
FriendDevices.put(btd.getId(),f.getId());
} catch (Exception ex) {}

for (Enumeration d = f.Devices.elements(); d.hasMoreElements();) {
try {
BluetoothDevice obtd = (BluetoothDevice)d.nextElement();
//appendString("-fd-p:" + btd.getId() + "-" + f.getId());
FriendDevices.put(obtd.getId(),f.getId());
} catch (Exception ex) {}
}

f.checkForUnreadMessages();

}
} catch (Exception ex) {
appendString("-rf-fd-ex: " + ex);
}
}

for (Enumeration e = WorldObjects.elements(); e.hasMoreElements();) {
try {
SpimeObject spo = (SpimeObject)e.nextElement();

if (spo.getClassId() == 4) {
Person p = (Person)spo;
try {
BluetoothDevice btd = new BluetoothDevice(p.FirstAddr.toString(), "", 1, 1);
//appendString("-fd-p:" + btd.getId() + "-" + f.getId());
PersonDevices.put(btd.getId(),p.getId());
} catch (Exception ex) {}

for (Enumeration d = p.Devices.elements(); d.hasMoreElements();) {
try {
BluetoothDevice obtd = (BluetoothDevice)d.nextElement();
//appendString("-fd-p:" + btd.getId() + "-" + p.getId());
PersonDevices.put(obtd.getId(),p.getId());
} catch (Exception ex) {
}
}

p.checkForUnreadMessages();

}
} catch (Exception ex) {
appendString("-rf-fd-ex: " + ex);
}
}


}

public String generateUid() {

int upperlimit = 100;
int lowerlimit = 0;
Random r = new Random();
int nr = (r.nextInt() >>> 1) % (upperlimit +1 - lowerlimit) + lowerlimit;

return "" + nr + localAddress + System.currentTimeMillis();

}


public String localDeviceId() {

//#ifdef config.ConnectToLocalhost:defined
return "fakemac"; //Application.fake_id
//#else
BluetoothDevice btd = new BluetoothDevice(localAddress, "",1,1);
return btd.getId();
//#endif
}

public static int classIdFromSpid(String spid) {
int ret = 0;

try {
String[] aStr = TextUtil.split(spid,'/');

ret = Integer.parseInt(aStr[2]);

} catch (Exception ex) {
}

return ret;
}

public Friend findFriendByPersonRef(String spid) {

try {

for (Enumeration e = LocalObjects.elements(); e.hasMoreElements(); ) {
SpimeObject spo = (SpimeObject)e.nextElement();

if (spo.getClassId() == 5) {
Friend f = (Friend)spo;
if (f.PersonRef.equals(spid)) return f;
}
}
} catch (Exception ex) {
}

return null;
}

public SpimeObject getSpimeObject(String spid) {

SpimeObject spo = null;
if (LocalObjects.containsKey(spid)) {
spo = (SpimeObject)LocalObjects.get(spid);
} else if (WorldObjects.containsKey(spid)) {
spo = (SpimeObject)WorldObjects.get(spid);
}

return spo;

}

public Person getPersonFromDeviceSpid(String spid) {

try {
//appendString("-look for person on:" + spid + "-");
if (PersonDevices.containsKey(spid)) {
//appendString("-person exist as device:" + PersonDevices.get(spid) + "-");
return (Person)WorldObjects.get(PersonDevices.get(spid));
}
} catch (Exception ex) {
appendString("-agpds-ex-");
}

return null;

}


public Person getLocalPerson() {
try {
if (LocalPerson == null) {

for (SpimePriorityEnumeration e = LocalObjects.prioritizedElements(); e.hasMoreElements();) {

SpimeObject s = (SpimeObject)e.nextElement();

if (s.getClassId() == 4) {
LocalPerson = (Person)s;
return LocalPerson;
}
}

return null;

}

} catch (Exception ex) {
appendString("-getLocalPerson-ex:" + ex + "-");
}

return LocalPerson;
}

public int getScreenWidth() {
if (SPM != null) {
return SPM.ScreenWidth;
} else { return 220; }

}

public void removeNotificationsByNoticeSpid(String noticeSpid) {
try {
for (Enumeration e = Notifications.elements(); e.hasMoreElements();) {
Notice n = (Notice)e.nextElement();
if (n.NoticeSpid.equals(noticeSpid)) {
n.Ack = 1;
n.setLogged(false);
WorldObjects.put(n.getId(),n);
Notifications.remove(n.getId());
return;
}
}
} catch (Exception ex) {

}
}

public void ComputeTrafficStats(long accumulate_bytes) {
bytes_since_login += accumulate_bytes;
bytes_this_session += accumulate_bytes;
}

}
Show details Hide details

Change log

r11 by claus.dahl on Feb 07, 2007   Diff
error screens - bandwidth logging
Go to: 
Project members, sign in to write a code review

Older revisions

r2 by claus.dahl on Feb 05, 2007   Diff
first drop
All revisions of this file

File info

Size: 47195 bytes, 1437 lines
Hosted by Google Code