summaryrefslogtreecommitdiff
path: root/src/plugins/android/src/com/motorola/studio/android/adt/DDMSFacade.java
blob: 31d6f14b4b5613d66e88e2e4e190bb96dca8dd21 (plain)
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
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.motorola.studio.android.adt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
import com.android.ddmlib.Client;
import com.android.ddmlib.ClientData;
import com.android.ddmlib.EmulatorConsole;
import com.android.ddmlib.FileListingService;
import com.android.ddmlib.FileListingService.FileEntry;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IDevice.DeviceState;
import com.android.ddmlib.MultiLineReceiver;
import com.android.ddmlib.SyncException;
import com.android.ddmlib.SyncService;
import com.android.ddmlib.SyncService.ISyncProgressMonitor;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
import com.android.ide.eclipse.ddms.DdmsPlugin;
import com.motorola.studio.android.AndroidPlugin;
import com.motorola.studio.android.adt.StudioAndroidEventManager.EventType;
import com.motorola.studio.android.common.IAndroidConstants;
import com.motorola.studio.android.common.exception.AndroidException;
import com.motorola.studio.android.common.log.StudioLogger;
import com.motorola.studio.android.i18n.AndroidNLS;
import com.motorola.studio.android.utilities.TelnetFrameworkAndroid;

/**
 * DESCRIPTION:
 * This class is the common interface to functionalities from DDMS  
 *
 * RESPONSIBILITY:
 * Centralizes the access to DDMS. 
 *
 * COLABORATORS:
 * None. 
 *
 * USAGE:
 * Use the public methods to use DDMS
 */
public class DDMSFacade
{
    /**
     * Command for switching back to USB connection mode.
     */
    private static final String USB_SWITCH_BACK_COMMAND = "usb"; //$NON-NLS-1$

    /**
     * Argument which indicates the device to apply a certain command. 
     */
    private static final String DEVICE_ID_INDICATOR = "-s"; //$NON-NLS-1$

    private static final String DEFAULT_WIRELESS_DEVICE_PROPERTY = "tiwlan0"; //$NON-NLS-1$

    /**
     * Map containing all connected devices.
     * It is being kept for us not to depend on ADT every time we need one, preventing 
     * deadlocks.
     */
    private static final Map<String, IDevice> connectedDevices = new HashMap<String, IDevice>();

    /**
     * Set containing the serial numbers of the devices completely loaded.
     * A device is considered completely loaded if it has already loaded the HOME application.
     */
    private static final Set<String> completelyUpDevices = new HashSet<String>();

    /**
     * Folder located inside the SDK folder containing some sdk tools.
     */
    static final String TOOLS_FOLDER = IAndroidConstants.FD_TOOLS;

    /**
     * Folder located inside the SDK folder and containing the ADB.
     */
    static final String PLATFORM_TOOLS_FOLDER = IAndroidConstants.FD_PLATFORM_TOOLS;

    /**
     * adb (android debug bridge) command.
     */
    static final String ADB_COMMAND = "adb"; //$NON-NLS-1$

    /**
     * Command to concatenate with "adb" to have the device shell.
     */
    static final String SHELL_CMD = "shell"; //$NON-NLS-1$

    /**
     * Options to be used with adb to indicate run operation.
     */
    private static final String AM_CMD = "am"; //$NON-NLS-1$

    /**
     * Command to concatenate with "am" to have an activity executed at the device.
     */
    private static final String START_CMD = "start"; //$NON-NLS-1$

    /**
     * Parameter for running in debug mode.
     */
    private static final String ADB_AM_DEBUG = "-D"; //$NON-NLS-1$

    /**
     * Parameter provided before the application package/name.
     */
    private static final String ADB_AM_NAME = "-n"; //$NON-NLS-1$

    /**
     * Parameter for selecting emulator instance.
     */
    static final String ADB_INSTANCE_PARAMETER = DEVICE_ID_INDICATOR; //$NON-NLS-1$

    /**
     * Folder for the SDK.
     */
    private static final String SDCARD_FOLDER = "sdcard"; //$NON-NLS-1$

    /**
     * Folder for the SDK.
     */
    private static final String MNT_SDCARD_FOLDER = "mnt/sdcard"; //$NON-NLS-1$

    /*
     * TCP/IP
     */
    private static final String CONNECT_TCPIP_CMD = "connect"; //$NON-NLS-1$

    private static final String DISCONNECT_TCPIP_CMD = "disconnect"; //$NON-NLS-1$

    private static final String TCPIP_CMD = "tcpip"; //$NON-NLS-1$

    private static final String IFCONFIG_CMD = "ifconfig"; //$NON-NLS-1$

    static Object consoleLock = new Object();

    private static Map<String, String> avdNameMap = new HashMap<String, String>();

    /**
     * Property from device which represents the wi-fi value to use ipconfig command.
     */
    private static final String WIFI_INTERFACE_DEVICE_PROPERTY = "wifi.interface"; //$NON-NLS-1$

    // IP validation
    private static final String ZERO_TO_255_PATTERN =
            "((\\d)|(\\d\\d)|([0-1]\\d\\d)|(2[0-4]\\d)|(25[0-5]))"; //$NON-NLS-1$

    private static final String IP_PATTERN = "(" + ZERO_TO_255_PATTERN + "\\." //$NON-NLS-1$ //$NON-NLS-2$
            + ZERO_TO_255_PATTERN + "\\." + ZERO_TO_255_PATTERN + "\\." + ZERO_TO_255_PATTERN //$NON-NLS-1$ //$NON-NLS-2$
            + ")+"; //$NON-NLS-1$

    /**
     * Must be called only once, during AndroidPlugin start-up.
     * This method configures all necessary device listeners. 
     */
    public static void setup()
    {
        AndroidPlugin.getDefault().addSDKLoaderListener(new Runnable()
        {

            public void run()
            {
                AndroidDebugBridge adb = AndroidDebugBridge.getBridge();
                if (adb == null)
                {
                    AndroidDebugBridge.disconnectBridge();
                    DdmsPlugin.setToolsLocation(AdtPlugin.getOsAbsoluteAdb(), true,
                            AdtPlugin.getOsAbsoluteHprofConv(), AdtPlugin.getOsAbsoluteTraceview());
                }

                if (adb != null)
                {
                    IDevice[] x = adb.getDevices();
                    IDevice[] newDevices = x;
                    List<IDevice> oldDevList = new ArrayList<IDevice>(connectedDevices.values());

                    for (IDevice newDev : newDevices)
                    {
                        String serialNum = newDev.getSerialNumber();
                        if (connectedDevices.containsKey(serialNum))
                        {
                            IDevice oldDev = connectedDevices.get(serialNum);
                            oldDevList.remove(oldDev);
                            if (oldDev.getState().compareTo((newDev).getState()) != 0)
                            {
                                if ((newDev).getState() == DeviceState.OFFLINE)
                                {
                                    deviceDisconnected(newDev);
                                }
                                else if ((newDev).getState() == DeviceState.ONLINE)
                                {
                                    deviceConnected(newDev);
                                }
                            }
                        }
                        else
                        {
                            deviceConnected(newDev);
                        }
                    }

                    for (IDevice oldDev : oldDevList)
                    {
                        deviceDisconnected(oldDev);
                    }
                }

            }
        });

        // Adds listener for the HOME application. It adds the serial number of the 
        // device to a collection when it identifies that the HOME application has
        // loaded
        AndroidDebugBridge.addClientChangeListener(new IClientChangeListener()
        {

            public void clientChanged(Client client, int changeMask)
            {
                if ((changeMask & Client.CHANGE_NAME) == Client.CHANGE_NAME)
                {
                    final Client finalClient = client;
                    Thread t = new Thread()
                    {

                        @Override
                        public void run()
                        {
                            String applicationName =
                                    finalClient.getClientData().getClientDescription();
                            if (applicationName != null)
                            {
                                IPreferenceStore store =
                                        AdtPlugin.getDefault().getPreferenceStore();
                                String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE);
                                if (home.equals(applicationName))
                                {
                                    String serialNum = finalClient.getDevice().getSerialNumber();
                                    synchronized (completelyUpDevices)
                                    {
                                        StudioLogger.debug("Completely Up Device: " + serialNum); //$NON-NLS-1$
                                        completelyUpDevices.add(serialNum);
                                    }
                                }
                            }
                        }
                    };
                    t.start();
                }
            }
        });
    }

    static void deviceStatusChanged(IDevice device)
    {
        StudioLogger.debug("Device changed: " + device.getSerialNumber()); //$NON-NLS-1$
        synchronized (connectedDevices)
        {
            connectedDevices.put(device.getSerialNumber(), device);
        }
        if ((device).getState() == DeviceState.ONLINE)
        {
            IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
            String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE);
            if (device.getClient(home) != null)
            {
                synchronized (completelyUpDevices)
                {
                    StudioLogger.debug("Completely Up Device: " + device.getSerialNumber()); //$NON-NLS-1$
                    if (!completelyUpDevices.contains(device.getSerialNumber()))
                    {
                        completelyUpDevices.add(device.getSerialNumber());
                    }
                }
            }
        }
    }

    /**
     * Registers a device as connected
     * 
     * @param device
     */
    static void deviceConnected(IDevice device)
    {
        final String serialNumber = device.getSerialNumber();
        StudioLogger.debug("Device connected: " + serialNumber); //$NON-NLS-1$
        synchronized (connectedDevices)
        {
            connectedDevices.put(serialNumber, device);
        }

        if (!device.isEmulator() && !device.hasClients())
        {
            boolean timeout = false;
            long startTime = System.currentTimeMillis();
            int maxInterval = 10000;
            do
            {
                try
                {
                    Thread.sleep(250);
                }
                catch (InterruptedException e)
                {
                    //do nothing
                }
                long currentTime = System.currentTimeMillis();
                timeout = ((startTime + maxInterval) < currentTime);

            }
            while (!device.hasClients() && !timeout);
            if (timeout)
            {
                synchronized (completelyUpDevices)
                {
                    //put the device up anyway.
                    completelyUpDevices.add(serialNumber);
                }
            }
        }

        if (device.hasClients())
        {
            // When a device is connected, look for the HOME application and add
            // the device serial number to a collection if it is already running.
            IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
            String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE);
            if (device.getClient(home) != null)
            {
                StudioLogger.debug("Completely Up Device: " + serialNumber); //$NON-NLS-1$
                synchronized (completelyUpDevices)
                {
                    completelyUpDevices.add(serialNumber);
                }
            }
        }

        StudioAndroidEventManager.fireEvent(EventType.DEVICE_CONNECTED, serialNumber);
    }

    /**
     * Unregisters a device as connected
     * 
     * @param device
     */
    static void deviceDisconnected(IDevice device)
    {
        final String serialNumber = device.getSerialNumber();
        StudioLogger.debug("Device disconnected: " + serialNumber); //$NON-NLS-1$
        synchronized (completelyUpDevices)
        {
            completelyUpDevices.remove(serialNumber);
        }
        synchronized (connectedDevices)
        {
            connectedDevices.remove(serialNumber);
        }
        StudioAndroidEventManager.fireEvent(EventType.DEVICE_DISCONNECTED, serialNumber);
        avdNameMap.remove(device.getSerialNumber());

    }

    /**
     * Get all connected device serial numbers
     * 
     * @return
     */
    public static Collection<String> getConnectedSerialNumbers()
    {
        return connectedDevices.keySet();
    }

    /**
     * Get the Device associated with the given serial number
     * 
     * @param serialNumber Serial number of the device to retrieve
     * @return Device associated with the given serial number
     */
    public static IDevice getDeviceBySerialNumber(String serialNumber)
    {
        return connectedDevices.get(serialNumber);
    }

    /**
     * Runs an activity at the given device
     * 
     * @param serialNumber The serial number of the device to have the activity executed
     * @param activityName The activity to execute
     * @param debugMode Whether the activity shall be run in debug mode or not
     * @param processOut The output stream of the process running "adb"
     * 
     * @return An IStatus object with the result of the operation
     */
    public static IStatus runActivity(String serialNumber, String activityName, boolean debugMode,
            OutputStream processOut)
    {
        IStatus status = Status.OK_STATUS;

        // Return if no instance is selected
        if (serialNumber == null)
        {
            StudioLogger.error("Abort run operation. Serial number is null."); //$NON-NLS-1$
            return new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID,
                    AndroidNLS.ERR_DDMSFacade_SerialNumberNullPointer);
        }

        // Return if instance is not started
        if (!isDeviceOnline(serialNumber))
        {
            StudioLogger.error("Abort run operation. Device is not online."); //$NON-NLS-1$
            return new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
        }

        try
        {
            String[] cmd = createRunCommand(serialNumber, activityName, debugMode);
            executeCommand(cmd, processOut);
        }
        catch (IOException e)
        {
            StudioLogger.error("Deploy: Could not execute adb install command."); //$NON-NLS-1$
            status = new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, e.getMessage());
        }

        return status;
    }

    static String executeCommand(String[] cmd, OutputStream out) throws IOException
    {
        return executeCommand(cmd, out, null);
    }

    /**
     * DOCUMENT ME!!
     * @param cmd
     * @param out
     * @param serialNumber 
     * @return
     * @throws IOException
     */
    static String executeCommand(String[] cmd, OutputStream out, String serialNumber)
            throws IOException
    {
        String fullCmd = ""; //$NON-NLS-1$
        if (out != null)
        {
            for (String cmdArg : cmd)
            {
                fullCmd += cmdArg + " "; //$NON-NLS-1$
            }
            out.write(fullCmd.getBytes());
            out.write("\n".getBytes()); //$NON-NLS-1$
        }

        Runtime r = Runtime.getRuntime();
        Process p = r.exec(cmd);

        String command_results = ""; //$NON-NLS-1$
        InputStream processIn = p.getInputStream();
        final BufferedReader br = new BufferedReader(new InputStreamReader(processIn));
        String line;
        try
        {
            while ((line = br.readLine()) != null)
            {
                command_results += line;
                command_results += "\n"; //$NON-NLS-1$
                if (out != null)
                {
                    if (serialNumber != null)
                    {
                        out.write((serialNumber + ": ").getBytes()); //$NON-NLS-1$
                    }
                    out.write(line.getBytes());
                    out.write("\n".getBytes()); //$NON-NLS-1$
                }
            }
        }
        finally
        {
            br.close();
        }

        return command_results;
    }

    /**
     * See http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
     * to understand how Process.exec works and its problems
     * 
     * @param cmd Command to be executed.
     * @param out Output Stream.
     * @param timeout Timeout (secs.)
     * @param monitor {@link IProgressMonitor}
     * 
     * @return the {@link IStatus} of this process execution.
     * 
     * @throws IOException Exception thrown in case there is any problem
     * executing the command.
     */
    private static IStatus executeRemoteDevicesCommand(String[] cmd, OutputStream out, int timeout,
            String timeoutMsg, IStopCondition stopCondition, IProgressMonitor monitor)
            throws IOException
    {

        IStatus status = Status.OK_STATUS;

        long timeoutLimit = -1;
        if (timeout != 0)
        {
            timeoutLimit = System.currentTimeMillis() + (timeout * 1000);
        }

        String fullCmd = ""; //$NON-NLS-1$
        for (String cmdArg : cmd)
        {
            fullCmd += cmdArg + " "; //$NON-NLS-1$
        }
        if (out != null)
        {
            out.write(fullCmd.getBytes());
            out.write("\n".getBytes()); //$NON-NLS-1$
        }

        Runtime r = Runtime.getRuntime();
        Process p = r.exec(cmd);

        int errorCode = 0;

        //  inputStream / errorStream;
        String[] commandResults = new String[]
        {
                "", "" //$NON-NLS-1$ //$NON-NLS-2$
        };

        commandResults =
                readCmdOutputFromStreams(commandResults[0], commandResults[1], p.getInputStream(),
                        p.getErrorStream(), out);

        while (!stopCondition.canStop())
        {
            if ((monitor != null) && (monitor.isCanceled()))
            {
                p.destroy();
                return Status.CANCEL_STATUS;
            }

            try
            {
                errorCode = p.exitValue();
                if (errorCode != 0)
                {
                    break;
                }

            }
            catch (IllegalThreadStateException e)
            {
                // Process is still running... Proceed with loop
            }

            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                StudioLogger.error("Execute command: thread has been interrupted"); //$NON-NLS-1$
            }

            if (timeout > 0)
            {
                try
                {
                    testTimeout(timeoutLimit, ((timeoutMsg != null) ? timeoutMsg
                            : AndroidNLS.ERR_GenericTimeout));
                }
                catch (TimeoutException e)
                {
                    p.destroy();
                    StudioLogger.debug("The timeout " + timeout //$NON-NLS-1$
                            + " has been reached when executing the command " + fullCmd); //$NON-NLS-1$
                    return new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, e.getMessage(), e);
                }
            }

        }

        commandResults =
                readCmdOutputFromStreams(commandResults[0], commandResults[1], p.getInputStream(),
                        p.getErrorStream(), out);

        if (errorCode != 0)
        {
            StudioLogger.debug("Command " + cmd + " returned an error code: " + errorCode); //$NON-NLS-1$ //$NON-NLS-2$
            status =
                    new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, NLS.bind(
                            AndroidNLS.ERR_CommandError, errorCode) + "\n" //$NON-NLS-1$
                            + ((!commandResults[1].equals("")) ? commandResults[1] //$NON-NLS-1$
                                    : commandResults[0]));
        }
        else
        {
            status = new Status(IStatus.OK, AndroidPlugin.PLUGIN_ID, commandResults[0]);
        }

        return status;
    }

    /**
     * Defines a stop condition
     */
    interface IStopCondition
    {
        public boolean canStop();
    }

    /**
     * @param commandResults
     * @param errorResults
     * @param inputStream
     * @param errorStream
     * @param out
     */
    private static String[] readCmdOutputFromStreams(String commandResults, String errorResults,
            InputStream inputStream, InputStream errorStream, OutputStream out)
    {
        String[] results = new String[2];
        String line = ""; //$NON-NLS-1$

        BufferedReader brInput = new BufferedReader(new InputStreamReader(inputStream));
        BufferedReader brError = new BufferedReader(new InputStreamReader(errorStream));

        try
        {

            // input stream
            if (brInput.ready())
            {
                while ((line = brInput.readLine()) != null)
                {
                    commandResults += line;
                    commandResults += "\n"; //$NON-NLS-1$
                    if (out != null)
                    {
                        out.write(line.getBytes());
                        out.write("\n".getBytes()); //$NON-NLS-1$
                    }
                }
            }

            // error stream
            if (brError.ready())
            {
                while ((line = brError.readLine()) != null)
                {
                    errorResults += "\n"; //$NON-NLS-1$
                    if (out != null)
                    {
                        out.write(line.getBytes());
                        out.write("\n".getBytes()); //$NON-NLS-1$
                    }
                }
            }
        }
        catch (IOException e)
        {
            StudioLogger.error("Cannot read command outputs"); //$NON-NLS-1$
        }
        finally
        {
            try
            {
                brInput.close();
                brError.close();
            }
            catch (IOException e)
            {
                StudioLogger.error("Could not close console stream: " + e.getMessage());
            }
        }

        results[0] = commandResults;
        results[1] = errorResults;

        return results;

    }

    /**
     * Checks if the timeout limit has reached.
     * 
     * @param timeoutLimit The system time limit that cannot be overtaken, in milliseconds.
     * @throws StartTimeoutException When the system time limit is overtaken. 
     */
    private static void testTimeout(long timeoutLimit, String timeoutErrorMessage)
            throws TimeoutException
    {
        if (System.currentTimeMillis() > timeoutLimit)
        {
            throw new TimeoutException(timeoutErrorMessage);
        }
    }

    /**
     * Creates a string with the command that should
     * be called in order to run the application.
     */
    private static String[] createRunCommand(String serialNumber, String activityName,
            boolean debugMode)
    {
        String cmd[];
        String sdkPath = SdkUtils.getSdkPath();

        // The tools folder should exist and be here, but double-cheking
        // once more wont kill
        File f = new File(sdkPath + PLATFORM_TOOLS_FOLDER + File.separator);
        if (!f.exists())
        {
            StudioLogger
                    .error("Run: Could not find tools folder on " + sdkPath + PLATFORM_TOOLS_FOLDER //$NON-NLS-1$
                            + File.separator);
        }
        else
        {
            if (!f.isDirectory())
            {
                StudioLogger.error("Run: Invalid tools folder " + sdkPath + PLATFORM_TOOLS_FOLDER //$NON-NLS-1$
                        + File.separator);
            }
        }

        String completeAppPath =
                activityName.substring(0, activityName.lastIndexOf(".")) + "/" + activityName; //$NON-NLS-1$ //$NON-NLS-2$
        if (debugMode)
        {
            // If debugMode option is checked, create command with the -D paramater
            String cmdTemp[] =
                    {
                            sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                            ADB_INSTANCE_PARAMETER, serialNumber, SHELL_CMD, AM_CMD, START_CMD,
                            ADB_AM_DEBUG, ADB_AM_NAME, completeAppPath
                    };
            cmd = cmdTemp;
        }
        else
        {
            // If debugMode option is unchecked, create command without the -D paramater
            String cmdTemp[] =
                    {
                            sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                            ADB_INSTANCE_PARAMETER, serialNumber, SHELL_CMD, AM_CMD, START_CMD,
                            ADB_AM_NAME, completeAppPath
                    };
            cmd = cmdTemp;
        }

        return cmd;
    }

    /**
     * Check if the device is Online (i.e. if it's possible to communicate with it)
     * Notice it is a verification of the status of the Device which may be different than the status of the Tml Instance.
     * 
     * @param serialNumber
     * @return true if the Device is online, false otherwise
     */
    public static boolean isDeviceOnline(String serialNumber)
    {
        IDevice device = getDeviceBySerialNumber(serialNumber);
        if ((device == null) || !device.isOnline())
        {
            return false;
        }
        return true;
    }

    /**
     * Return true if the Device is being shown on the OFFLINE state.
     * 
     * @param serialNumber Device´s serial number.
     * 
     * @return <code>true</code> in case the Device if offline,
     * <code>false</code> otherwise.
     */
    public static boolean isDeviceOffline(String serialNumber)
    {

        IDevice device = getDeviceBySerialNumber(serialNumber);
        return ((device == null) || ((device != null) && device.isOffline()));
    }

    /**
     * Check if the device is completely loaded
     * A device is completely loaded when it loads the HOME application
     *  
     * @param serialNumber
     * @return true if the Device has completely loaded; false otherwise
     */
    public static boolean isDeviceCompletelyLoaded(String serialNumber)
    {
        return completelyUpDevices.contains(serialNumber);
    }

    /**
     * Tests if the device represented by the serial number (if it exists) is an emulator
     * 
     * @param serialNumber
     * @return true if it is an emulator, false if not or non existent
     */
    public static boolean isEmulator(String serialNumber)
    {
        IDevice device = getDeviceBySerialNumber(serialNumber);
        if ((device != null) && device.isEmulator())
        {
            return true;
        }
        return false;
    }

    public static boolean isRemote(String serialNumber)
    {
        // firstly, test if the serial number has the format "anything:digits"
        Pattern p = Pattern.compile("(.)+:(\\d)+"); //$NON-NLS-1$
        Matcher m = p.matcher(serialNumber);
        if (m.matches())
        {
            IDevice device = getDeviceBySerialNumber(serialNumber);
            if ((device != null) && !device.isEmulator())
            {
                return true;
            }
        }

        return false;
    }

    /**
     * Execute an app in the Device
     * 
     * @param serialNumber Serial number of the device where to execute the command
     * @param remoteCommand command to be executed remotely on the Device
     * @param monitor monitor associated with the operation
     * 
     * @return The lines read from the command output 
     * 
     * @throws IOException
     */
    public static Collection<String> execRemoteApp(String serialNumber, String remoteCommand,
            final IProgressMonitor monitor) throws IOException
    {
        return executeShellCmd(serialNumber, remoteCommand, monitor);
    }

    /**
     * Execute an app in the Device
     * 
     * @param serialNumber Serial number of the device where to execute the command
     * @param remoteCommands commands to be executed remotely on the Device
     * @param monitor monitor associated with the operation
     * 
     * @throws IOException
     */
    public static Map<String, Collection<String>> execRemoteApp(String serialNumber,
            Collection<String> remoteCommands, final IProgressMonitor monitor) throws IOException
    {
        Map<String, Collection<String>> cmdAnswers =
                new LinkedHashMap<String, Collection<String>>();
        for (String remoteCommand : remoteCommands)
        {
            StudioLogger.debug(remoteCommand);
            Collection<String> answers = executeShellCmd(serialNumber, remoteCommand, monitor);
            cmdAnswers.put(remoteCommand, answers);
        }

        return cmdAnswers;
    }

    private static Collection<String> executeShellCmd(String serialNumber, final String cmd,
            final IProgressMonitor monitor)
    {
        final Collection<String> results = new ArrayList<String>();
        IDevice d = getDeviceBySerialNumber(serialNumber);
        if (d != null)
        {
            try
            {
                d.executeShellCommand(cmd, new MultiLineReceiver()
                {
                    public boolean isCancelled()
                    {
                        return monitor.isCanceled();
                    }

                    @Override
                    public void processNewLines(String[] lines)
                    {
                        for (String line : lines)
                        {
                            if ((!line.equals("")) && (!line.equals(cmd))) //$NON-NLS-1$
                            {
                                results.add(line);
                            }
                        }
                    }
                }, 0);
            }
            catch (Exception e)
            {
                StudioLogger.error(DDMSFacade.class, "Error executing shell command " + cmd //$NON-NLS-1$
                        + " at device " + serialNumber, e); //$NON-NLS-1$
            }
        }
        return results;
    }

    /**
     * Retrieves all properties from the device with provided serial number.
     * @param serialNumber
     * @return
     */
    public static Properties getDeviceProperties(String serialNumber)
    {
        Properties instanceProperties = new Properties();
        if (serialNumber != null)
        {
            String key = ""; //$NON-NLS-1$
            String value = ""; //$NON-NLS-1$
            Collection<String> lines;
            try
            {
                lines = execRemoteApp(serialNumber, "getprop", new NullProgressMonitor()); //$NON-NLS-1$

                for (String line : lines)
                {
                    String[] split = line.split("]:"); //$NON-NLS-1$
                    if (split.length >= 2)
                    {
                        if (!split[0].equals("")) //$NON-NLS-1$
                        {
                            key = split[0].substring(1, split[0].length());
                            if (!split[1].equals("")) //$NON-NLS-1$
                            {
                                value = split[1].substring(2, split[1].length() - 1);
                                instanceProperties.setProperty(key, value);
                            }
                        }

                    }
                }
            }
            catch (IOException e)
            {
                StudioLogger.error("IOException while executing an app on device. "
                        + e.getMessage());
            }
        }
        return instanceProperties;
    }

    /**
    * Retrieves a given property from the device with provided serial number.
    * 
    * @param serialNumber
    * @param propertyName
    * 
    * @return
    */
    public static String getDeviceProperty(String serialNumber, String propertyName)
    {
        String result = null;
        IDevice device = DDMSFacade.getDeviceBySerialNumber(serialNumber);
        if (device != null)
        {
            result = device.getProperty(propertyName);
        }
        return result;
    }

    /**
     * Get the name of the VM associated to the emulator running in the given deviceSerial identification.
     * 
     * @param deviceSerial identification of the emulator whose vm name must be retrieved.
     * @return the name of the VM used by the emulator running with the given id, 
     * or null if the vmname could be retrieved.
     */
    public static String getVmName(final IDevice d)
    {
        String vmName = null;
        String serialNumber = d.getSerialNumber();
        int MAX_TRIES = 120;
        int tries = 0;

        while ((vmName == null) && (tries < MAX_TRIES))
        {
            synchronized (avdNameMap)
            {
                vmName = avdNameMap.get(serialNumber);
            }

            if (vmName == null)
            {
                vmName = d.getAvdName();
            }

            if (vmName == null)
            {
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e)
                {
                    //do nothing
                }
                finally
                {
                    tries++;
                }
            }

            //try to get vmname by telnet as last option
            if (vmName == null)
            {
                vmName = getVmNameByTelnet(serialNumber);
            }

        }

        if (vmName != null)
        {
            synchronized (avdNameMap)
            {
                if (avdNameMap.get(serialNumber) == null)
                {
                    avdNameMap.put(serialNumber, vmName);
                }
            }

        }

        return vmName;
    }

    private static String getVmNameByTelnet(String serialNumber)
    {
        Pattern pattern = Pattern.compile("emulator-([0-9]+)"); //$NON-NLS-1$
        TelnetFrameworkAndroid telnet = new TelnetFrameworkAndroid();
        Matcher matcher = pattern.matcher(serialNumber);
        matcher.matches();
        String avdName = null;

        try
        {
            Integer telnetPort = Integer.valueOf(matcher.group(1));
            telnet.connect("localhost", telnetPort); //$NON-NLS-1$
            String avdNameRaw = telnet.write("avd name\r\n", new String[] //$NON-NLS-1$
                    {
                        "KO" //$NON-NLS-1$
                });

            String split = avdNameRaw.contains("\r\n") ? "\r\n" : "\n";

            String[] outputArray = avdNameRaw.split(split); //$NON-NLS-1$
            if (outputArray.length > 2)
            {
                avdName = outputArray[2];
            }

            if (avdName != null)
            {
                avdNameMap.put(serialNumber, avdName);
            }
        }
        catch (NumberFormatException e)
        {
            avdName = serialNumber;
        }
        catch (IOException e)
        {
            avdName = serialNumber;
        }
        finally
        {
            try
            {
                telnet.disconnect();
            }
            catch (IOException e)
            {
                //Do nothing.
            }
        }
        return avdName;
    }

    /**
     * Get the Device associated with the Android VM
     * 
     * @param vmName Android VM name
     * @return Device associated with the given Android VM
     */
    public static IDevice getDeviceWithVmName(String vmName)
    {
        IDevice toReturn = null;
        if (vmName != null)
        {
            Collection<IDevice> devices = connectedDevices.values();
            for (IDevice d : devices)
            {
                if (d.isEmulator())
                {
                    String deviceVmName = DDMSFacade.getVmName(d);
                    if (vmName.equals(deviceVmName))
                    {
                        toReturn = d;
                        break;
                    }
                }
            }
        }
        return toReturn;
    }

    /**
     * Securely get the name of the AVD associated to the given device.
     * 
     * @param serialNumber The serialNumber of the device that we want the AVD name for
     * @return the name of the AVD used by the emulator running with the given device, 
     * or null if the vmname could be retrieved.
     */
    public static String getNameBySerialNumber(String serialNumber)
    {
        String avdName = null;
        IDevice d = getDeviceBySerialNumber(serialNumber);
        avdName = getNameByDevice(d);

        return avdName;
    }

    /**
     * Securely get the serial number of the given instance.
     * 
     * @param instanceName The name of the instance we want the serial number of
     * @return the serial number of the given instance, or <code>null</code> if no instance with the 
     * given name is online
     */
    public static String getSerialNumberByName(String instanceName)
    {
        String serialNumber = null;
        if (instanceName != null)
        {
            List<IDevice> devices = null;
            synchronized (connectedDevices)
            {
                devices = new ArrayList<IDevice>(connectedDevices.size());
                devices.addAll(connectedDevices.values());
            }
            if (devices != null)
            {
                for (IDevice dev : devices)
                {
                    if (instanceName.equals(getNameByDevice(dev)))
                    {
                        serialNumber = dev.getSerialNumber();
                        break;
                    }
                }
            }
        }

        return serialNumber;
    }

    public static Collection<String> getRunningApplications(String serialNumber)
    {
        Collection<String> apps = new ArrayList<String>();
        if (serialNumber != null)
        {
            IDevice dev = getDeviceBySerialNumber(serialNumber);
            if (dev != null)
            {
                Client[] clients = dev.getClients();
                if ((clients != null) && (clients.length > 0))
                {
                    for (Client c : clients)
                    {
                        apps.add(c.getClientData().getClientDescription());
                    }
                }
            }
        }

        return apps;
    }

    /**
     * Dumps a HPROF file based on a client description and a device serial number
     * @param clientDescription A client description of a running application
     */
    public static IStatus dumpHprofFile(String clientDescription, String serialNumber,
            IProgressMonitor monitor)
    {
        IStatus status = Status.OK_STATUS;
        monitor.beginTask(AndroidNLS.DumpHprofFile_GeneratingMemoryAnalysisOutput, 100);

        // Retrive running apps
        monitor.setTaskName(AndroidNLS.DumpHprofFile_GettingRunningApplications);
        IDevice dev = getDeviceBySerialNumber(serialNumber);
        Client[] clients = dev.getClients();
        monitor.worked(25);

        // Store the shell
        final Shell[] shell = new Shell[1];

        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable()
        {
            public void run()
            {

                shell[0] = new Shell(PlatformUI.getWorkbench().getDisplay());

            }
        });

        MotodevHProfDumpHandler hprofHandler = new MotodevHProfDumpHandler(shell[0], monitor);
        monitor.setTaskName(AndroidNLS.DumpHprofFile_SettingApplicationToAnalyse);
        hprofHandler.setSelectedApp(clientDescription);
        monitor.worked(25);

        try
        {
            // Find a client with matching description and dum the HPROF file
            for (Client c : clients)
            {
                if (c.getClientData().getClientDescription().equals(clientDescription))
                {
                    // Set our handler as the HprofDumpHandler
                    ClientData.setHprofDumpHandler(hprofHandler);
                    monitor.setTaskName(AndroidNLS.DumpHprofFile_DumpingHprofFile);
                    c.dumpHprof();
                    synchronized (DDMSFacade.class)
                    {
                        DDMSFacade.class.wait();
                    }

                    monitor.worked(50);
                }
            }
        }
        catch (Exception e)
        {
            // Status not ok
            status = Status.CANCEL_STATUS;
        }
        finally
        {
            monitor.done();
        }

        return status;

    }

    /**
     * Gets the AVD name of the device
     * 
     * @param d The device to be searched for the AVD name
     * 
     * @return The AVD name
     */
    private static String getNameByDevice(final IDevice d)
    {
        String name = null;
        if (d != null)
        {
            if (d.isEmulator())
            {

                name = getVmName(d);
            }
            else
            {
                name = d.getSerialNumber();
            }
        }

        return name;
    }

    /**
     * Create port forward for a given VM
     * 
     * @param serialNumber Android serial number
     * @param from port number from
     * @param to port number to
     * @return true is the port forward was successful, false otherwise
     */
    public static boolean createForward(String serialNumber, int from, int to)
    {
        boolean ok = true;
        IDevice device = getDeviceBySerialNumber(serialNumber);
        try
        {
            device.createForward(from, to);
        }
        catch (Exception e)
        {
            StudioLogger.error(DDMSFacade.class, "Error creating forward of device: " //$NON-NLS-1$
                    + serialNumber + " from " + from + " to " + to, e); //$NON-NLS-1$ //$NON-NLS-2$
            ok = false;
        }
        return ok;
    }

    /**
     * Kill the communication channel
     * 
     * @param serialNumber The serial number of the device to kill
     */
    public static void kill(String serialNumber)
    {
        if (isDeviceOnline(serialNumber))
        {
            IDevice deviceToKill = getDeviceBySerialNumber(serialNumber);
            if (deviceToKill != null)
            {
                synchronized (consoleLock)
                {
                    EmulatorConsole console = EmulatorConsole.getConsole(deviceToKill);
                    if (console != null)
                    {
                        console.kill();
                    }
                }
            }
        }
    }

    /**
     * Push files to device
     * 
     * @param serialNumber Android device serial number
     * @param localDir local folder path
     * @param fileNames files to transfer
     * @param remoteDir destination folder path
     * @param timeout timeout for the operation
     * @param monitor monitor associated with the operation
     */
    public static IStatus pushFiles(String serialNumber, String localDir,
            Collection<String> fileNames, String remoteDir, int timeout,
            final IProgressMonitor monitor, OutputStream outputStream)
    {
        return transferFiles(true, serialNumber, localDir, fileNames, remoteDir, timeout, monitor,
                outputStream);
    }

    /**
     * Push files to device
     * 
     * @param serialNumber Android device serial number
     * @param localFiles destination local files 
     * @param remoteFiles remote files to transfer as localFiles to desktop
     * @param timeout timeout for the operation
     * @param monitor monitor associated with the operation
     */
    public static IStatus pushFiles(String serialNumber, List<File> localFiles,
            List<String> remoteFiles, int timeout, final IProgressMonitor monitor,
            OutputStream outputStream)
    {
        return transferFiles(true, serialNumber, localFiles, remoteFiles, timeout, monitor,
                outputStream);
    }

    /**
     * Pull files from device
     * 
     * @param serialNumber Android device serial number
     * @param localDir local folder path
     * @param fileNames files to transfer
     * @param remoteDir destination folder path
     * @param timeout timeout for the operation
     * @param monitor monitor associated with the operation
     */
    public static IStatus pullFiles(String serialNumber, String localDir,
            Collection<String> fileNames, String remoteDir, int timeout,
            final IProgressMonitor monitor, OutputStream outputStream)
    {
        return transferFiles(false, serialNumber, localDir, fileNames, remoteDir, timeout, monitor,
                outputStream);
    }

    /**
     * Pull files from device
     * 
     * @param serialNumber Android device serial number
     * @param localFiles local files to transfer as remoteFiles to device
     * @param remoteFiles destination remote files
     * @param timeout timeout for the operation
     * @param monitor monitor associated with the operation
     */
    public static IStatus pullFiles(String serialNumber, List<File> localFiles,
            List<String> remoteFiles, int timeout, final IProgressMonitor monitor,
            OutputStream outputStream)
    {
        return transferFiles(false, serialNumber, localFiles, remoteFiles, timeout, monitor,
                outputStream);
    }

    /**
     * Get the service used to transfer files to the Device
     * 
     * @param device Device
     * @param timeout timeout for the operation
     * @param monitor monitor associated with the operation
     * @return The service used to transfer files to the Device
     * 
     * @throws AndroidException
     */
    private static SyncService getSyncService(IDevice device, int timeout,
            final IProgressMonitor monitor) throws AndroidException
    {

        SyncService service = null;
        long timeoutLimit = System.currentTimeMillis() + timeout;
        do
        {
            if ((device != null) && (device.isOnline()))
            {
                try
                {
                    service = device.getSyncService();
                }
                catch (IOException e)
                {
                    StudioLogger.debug("Couldn't get sync service; cause: " + e.getMessage()); //$NON-NLS-1$
                }
                catch (com.android.ddmlib.TimeoutException e)
                {
                    StudioLogger.debug("Couldn't get sync service; cause: " + e.getMessage()); //$NON-NLS-1$
                }
                catch (AdbCommandRejectedException e)
                {
                    StudioLogger.debug("Couldn't get sync service; cause: " + e.getMessage()); //$NON-NLS-1$
                }
            }

            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                //do nothing
            }

            if (monitor.isCanceled())
            {
                StudioLogger.info("Operation canceled by the user"); //$NON-NLS-1$
                return null;
            }

            if (System.currentTimeMillis() > timeoutLimit)
            {
                StudioLogger.error("The emulator was not up within the set timeout"); //$NON-NLS-1$
                throw new AndroidException(
                        "Timeout while preparing to transfer files to the Device. " + device); //$NON-NLS-1$
            }
        }
        while (service == null);

        return service;
    }

    private static IStatus transferFiles(boolean isPush, String serialNumber, String localDir,
            Collection<String> fileNames, String remoteDir, int timeout,
            final IProgressMonitor monitor, OutputStream outputStream)
    {
        List<File> localList = new ArrayList<File>();
        List<String> remoteList = new ArrayList<String>();
        for (String name : fileNames)
        {
            localList.add(new File(localDir, name));
            remoteList.add(remoteDir + "/" + name); //$NON-NLS-1$
        }
        return transferFiles(isPush, serialNumber, localList, remoteList, timeout, monitor,
                outputStream);
    }

    private static IStatus transferFiles(boolean isPush, String serialNumber,
            List<File> localFiles, List<String> remoteFiles, int timeout,
            final IProgressMonitor monitor, OutputStream outputStream)
    {
        if (localFiles.size() != remoteFiles.size())
        {
            return new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID,
                    AndroidNLS.ERR_DDMSFacade_IncompatibleFileLists);
        }

        IStatus status = Status.OK_STATUS;
        IDevice device = DDMSFacade.getDeviceBySerialNumber(serialNumber);

        SyncService service = null;
        try
        {
            service = getSyncService(device, timeout, monitor);
            if (service == null)
            {
                status = Status.CANCEL_STATUS;
            }
            else
            {
                final ISyncProgressMonitor syncMonitor = new ISyncProgressMonitor()
                {
                    public void start(int i)
                    {
                        //do nothing
                    }

                    public void stop()
                    {
                        //do nothing
                    }

                    public void advance(int i)
                    {
                        //do nothing
                    }

                    public boolean isCanceled()
                    {
                        return monitor.isCanceled();
                    }

                    public void startSubTask(String s)
                    {
                        //do nothing
                    }
                };

                FileListingService flService = device.getFileListingService();

                for (int i = 0; i < localFiles.size(); i++)
                {
                    File localFile = localFiles.get(i);
                    String remotePath = remoteFiles.get(i);
                    String absLocalFile = localFile.getAbsolutePath();

                    String resultMessage = null;
                    if (isPush)
                    {
                        StudioLogger.debug("Push " + absLocalFile + " to " + remotePath); //$NON-NLS-1$ //$NON-NLS-2$
                        try
                        {
                            service.pushFile(absLocalFile, remotePath, syncMonitor);
                        }
                        catch (SyncException e1)
                        {
                            StudioLogger
                                    .debug("Push result: " + "SyncException occured " + e1.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
                            resultMessage =
                                    NLS.bind(AndroidNLS.CON_ConsolePush, absLocalFile, remotePath)
                                            + ": " + e1.getLocalizedMessage(); //$NON-NLS-1$
                        }
                        catch (FileNotFoundException e1)
                        {
                            StudioLogger.debug("Push result: " + "FileNotFoundException occured " //$NON-NLS-1$ //$NON-NLS-2$
                                    + e1.getMessage());
                            resultMessage =
                                    NLS.bind(AndroidNLS.CON_ConsolePush, absLocalFile, remotePath)
                                            + ": " + e1.getLocalizedMessage(); //$NON-NLS-1$
                        }
                        catch (IOException e1)
                        {
                            StudioLogger
                                    .debug("Push result: " + "IOException occured " + e1.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
                            resultMessage =
                                    NLS.bind(AndroidNLS.CON_ConsolePush, absLocalFile, remotePath)
                                            + ": " + e1.getLocalizedMessage(); //$NON-NLS-1$
                        }
                        catch (com.android.ddmlib.TimeoutException e1)
                        {
                            StudioLogger
                                    .debug("Push result: " + "TimeoutException occured " + e1.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
                            resultMessage =
                                    NLS.bind(AndroidNLS.CON_ConsolePush, absLocalFile, remotePath)
                                            + ": " + e1.getLocalizedMessage(); //$NON-NLS-1$
                        }

                        if ((outputStream != null) && (resultMessage != null))
                        {
                            try
                            {
                                outputStream.write(resultMessage.getBytes());
                                outputStream.write('\n');
                                outputStream.flush();
                            }
                            catch (Exception e)
                            {
                                // Do nothing
                            }
                        }

                    }
                    else
                    {
                        FileEntry f1 = null;
                        FileEntry f2 = null;

                        f2 = flService.getRoot();
                        flService.getChildren(f2, false, null);
                        String[] dirs = remotePath.split("/"); //$NON-NLS-1$

                        for (int j = 1; j < (dirs.length - 1); j++)
                        {
                            f1 = f2.findChild(dirs[j]);
                            flService.getChildren(f1, false, null);
                            f2 = f1;
                        }

                        final FileEntry fileToPull = f2.findChild(dirs[dirs.length - 1]);

                        if (fileToPull != null)
                        {
                            try
                            {
                                service.pullFile(fileToPull, absLocalFile, syncMonitor);
                            }
                            catch (FileNotFoundException e)
                            {
                                resultMessage = e.getLocalizedMessage();
                                StudioLogger.debug("Pull result: " + e.getMessage()); //$NON-NLS-1$
                            }
                            catch (SyncException e)
                            {
                                resultMessage = e.getLocalizedMessage();
                                StudioLogger.debug("Pull result: " + e.getMessage()); //$NON-NLS-1$
                            }
                            catch (IOException e)
                            {
                                resultMessage = e.getLocalizedMessage();
                                StudioLogger.debug("Pull result: " + e.getMessage()); //$NON-NLS-1$
                            }
                            catch (com.android.ddmlib.TimeoutException e)
                            {
                                resultMessage = e.getLocalizedMessage();
                                StudioLogger.debug("Pull result: " + e.getMessage()); //$NON-NLS-1$
                            }

                            if ((outputStream != null) && (resultMessage != null))
                            {
                                String message =
                                        NLS.bind(AndroidNLS.CON_ConsolePull,
                                                fileToPull.getFullPath(), absLocalFile)
                                                + ": " + resultMessage; //$NON-NLS-1$
                                try
                                {
                                    outputStream.write(message.getBytes());
                                    outputStream.write('\n');
                                    outputStream.flush();
                                }
                                catch (IOException e)
                                {
                                    //do nothing
                                }
                            }
                        }
                        else
                        {
                            resultMessage =
                                    NLS.bind(AndroidNLS.DDMSFacade_Remote_File_Not_Found,
                                            remotePath);
                            StudioLogger.debug("Pull result: File not found " + remotePath); //$NON-NLS-1$
                        }
                    }

                    if (resultMessage != null)
                    {
                        status = new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, resultMessage);
                    }
                    if (syncMonitor.isCanceled())
                    {
                        status = Status.CANCEL_STATUS;
                        break;
                    }
                }
            }
        }
        catch (AndroidException e)
        {
            status = new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID, e.getMessage());
        }
        catch (NullPointerException e1)
        {
            status =
                    new Status(IStatus.ERROR, AndroidPlugin.PLUGIN_ID,
                            AndroidNLS.ERR_DDMSFacade_FileNotFound);
        }
        finally
        {
            if (service != null)
            {
                service.close();
            }
        }

        return status;
    }

    /**
     * Check if the application is running in the device with specified serial number
     * @param serialNumber
     * @param applicationName
     * @return true if it is running, false otherwise
     */
    public static boolean isApplicationRunning(String serialNumber, String applicationName)
    {
        IDevice dev = null;
        boolean running = false;
        dev = connectedDevices.get(serialNumber);
        if (dev != null)
        {
            running = dev.getClient(applicationName) != null;
        }
        return running;
    }

    /**
     * Connect to a Remote Device given its IP/Port
     * 
     * @param device the Remote Device Instance
     * @param host device host (IP)
     * @param port device port
     * @param timeout the maximum time allowed to successfully connect to the device
     * @param monitor the monitor of the operation
     * @return the status of the operation
     * @throws IOException
     */
    public static IStatus connectTcpIp(final ISerialNumbered device, String host, String port,
            int timeout, IProgressMonitor monitor) throws IOException
    {
        SubMonitor subMonitor = SubMonitor.convert(monitor, 1000);

        subMonitor.beginTask(AndroidNLS.DDMSFacade_MsgConnectingToDeviceViaTCPIP, 10);

        IStatus status = Status.OK_STATUS;

        String serialNumber = device.getSerialNumber();
        if (!isDeviceOnline(serialNumber)) // check if it's already connected
        {
            String[] cmd = createConnectTcpIpCommand(host, port);

            status =
                    executeRemoteDevicesCommand(
                            cmd,
                            null,
                            timeout,
                            NLS.bind(AndroidNLS.ERR_RemoteDevice_TimeoutWhileConnecting,
                                    device.getDeviceName()), new IStopCondition()
                            {

                                public boolean canStop()
                                {
                                    String serialNumber = device.getSerialNumber();
                                    if (serialNumber != null)
                                    {
                                        return isDeviceOnline(serialNumber);
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }, subMonitor.newChild(1000));

        }

        subMonitor.worked(1000);

        return status;
    }

    /**
     * Method which switches the device connection mode from TCP/IP
     * to USB.
     * 
     * @param device {@link ISerialNumbered} device to have its connection mode changed.
     * @param host The IP of the device.
     * @param port The port in which the TCP/IP connection is established.
     * @param timeout The maximum time which the switching operation is attempted.
     * @param monitor The {@link IProgressMonitor} which this operation is being computed.
     * 
     * @return Returns the {@link IStatus} of this operation.
     * 
     * @throws IOException Exception thrown in case something goes wrong while trying
     * to switch the device connection mode from TCP/IP to USB.
     */
    public static IStatus switchFromTCPConnectionModeToUSBConnectionMode(
            final ISerialNumbered device, String host, String port, int timeout,
            IProgressMonitor monitor) throws IOException
    {
        SubMonitor subMonitor = SubMonitor.convert(monitor, 1000);

        subMonitor.beginTask(AndroidNLS.DDMSFacade_MsgSwitchingDeviceFromTCPIPToUSB, 10);

        IStatus status = Status.OK_STATUS;

        String serialNumber = device.getSerialNumber();
        if (isDeviceOnline(serialNumber)) // check if it's already connected
        {
            String[] cmd = createSwitchToUSBConnectionModeCommand(host, port);

            status =
                    executeRemoteDevicesCommand(cmd, null, timeout, NLS.bind(
                            AndroidNLS.DDMSFacade_MsgTimeoutReachedSwitchingFromTCPToUSB,
                            device.getDeviceName()), new IStopCondition()
                    {

                        public boolean canStop()
                        {
                            String serialNumber = device.getSerialNumber();
                            if (serialNumber != null)
                            {
                                return isDeviceOnline(serialNumber);
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }, subMonitor.newChild(1000));

        }

        subMonitor.worked(1000);

        if (status.isOK())
        {
            StudioLogger.collectUsageData(StudioLogger.WHAT_REMOTE_USB,
                    StudioLogger.KIND_REMOTE_DEVICE, StudioLogger.DESCRIPTION_DEFAULT,
                    AndroidPlugin.PLUGIN_ID, AndroidPlugin.getDefault().getBundle().getVersion()
                            .toString());
        }

        return status;
    }

    /**
     * Get the wireless ip from the connected handset
     * @param serialNumber
     * @param monitor
     * @return the ip or null if not possible to retrieve it
     */
    public static String getWirelessIPfromHandset(String serialNumber, IProgressMonitor monitor)
    {
        String handset_wireless_ip = null;
        IDevice device = null;

        device = connectedDevices.get(serialNumber);
        if (device != null)
        {
            // get the wi-fi name for executing the ipconfig command
            String wifiProperty = device.getProperty(WIFI_INTERFACE_DEVICE_PROPERTY);
            if (wifiProperty == null)
            {
                wifiProperty = DEFAULT_WIRELESS_DEVICE_PROPERTY;
            }
            // execute ipconfig command
            Collection<String> answers =
                    executeShellCmd(serialNumber, IFCONFIG_CMD + " " + wifiProperty, monitor); //$NON-NLS-1$

            // Success message - for example
            // [tiwlan0: ip 192.168.0.174 mask 255.255.255.0 flags [up broadcast running multicast]]

            if (answers != null)
            {
                String result = answers.toString();
                if (result != null)
                {
                    // splits the result of the shell command and gets the third position 
                    // that should be the IP number
                    String[] result_splited = result.split(" "); //$NON-NLS-1$
                    if (result_splited.length >= 3)
                    {
                        // check whether there is an IP
                        Pattern pattern = Pattern.compile(IP_PATTERN);
                        Matcher matcher = pattern.matcher(result);
                        if (matcher.find())
                        {
                            handset_wireless_ip = result_splited[2];
                        }
                    }
                }
            }
        }
        return handset_wireless_ip;
    }

    /**
     * Switch adb connection mode of an specific device to TCPIP
     * 
     * @param deviceName name of the handset instance
     * @param host wireless ip of the handset instance
     * @param port number of the port to be using during the connection
     * @param timeout the maximum time allowed to successfully connect to the device
     * @param monitor the monitor of the operation
     * @return the status of the operation
     * 
     * @throws IOException Exception thrown in case there are problems switching the device.
     */
    public static IStatus switchUSBtoTcpIp(String deviceName, final String serialNumber,
            String port, int timeout, IProgressMonitor monitor) throws IOException
    {
        SubMonitor subMonitor = SubMonitor.convert(monitor, 1000);

        subMonitor.beginTask(AndroidNLS.DDMSFacade_MsgSwitchingFromUSBConnection, 10);

        IStatus status = Status.OK_STATUS;

        if (isDeviceOnline(serialNumber))
        {
            String[] cmd = createSwitchToTcpIpCommand(serialNumber, port);

            status =
                    executeRemoteDevicesCommand(cmd, null, timeout,
                            NLS.bind(AndroidNLS.ERR_WirelessRemoteDevice_TimeoutWhileConnecting,
                                    deviceName), new IStopCondition()
                            {

                                public boolean canStop()
                                {
                                    if (serialNumber != null)
                                    {
                                        return isDeviceOffline(serialNumber);
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }, subMonitor.newChild(1000));

        }

        monitor.worked(1000);

        return status;
    }

    /**
     * Disconnect from a Remote Device given its IP/Port
     * 
     * @param device the Remote Device Instance
     * @param host device host (IP)
     * @param port device port
     * @param timeout the maximum time allowed to successfully disconnect from the device
     * @param monitor the monitor of the operation
     * @return the status of the operation
     * @throws IOException
     */
    public static IStatus disconnectTcpIp(final ISerialNumbered device, String host, String port,
            int timeout, IProgressMonitor monitor) throws IOException
    {
        IStatus status = Status.OK_STATUS;

        String serialNumber = device.getSerialNumber();
        if (isDeviceOnline(serialNumber)) // check if it's already disconnected
        {
            String[] cmd = createDisconnectTcpIpCommand(host, port);

            status =
                    executeRemoteDevicesCommand(
                            cmd,
                            null,
                            timeout,
                            NLS.bind(AndroidNLS.ERR_RemoteDevice_TimeoutWhileDisconnecting,
                                    device.getDeviceName()), new IStopCondition()
                            {

                                public boolean canStop()
                                {
                                    String serialNumber = device.getSerialNumber();
                                    return !isDeviceOnline(serialNumber);
                                }
                            }, monitor);

        }

        return status;
    }

    /**
     * Creates a string with the command that should
     * be called in order to connect to an IP/Port
     * 
     * @param host device host (IP)
     * @param port device port
     * @return the command to be used to connect to an IP/Port
     */
    private static String[] createConnectTcpIpCommand(String host, String port)
    {

        String hostPort = host + ":" + port; //$NON-NLS-1$

        String sdkPath = SdkUtils.getSdkPath();

        String cmd[] =
                {
                        sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                        CONNECT_TCPIP_CMD, hostPort
                };

        return cmd;
    }

    /**
     * Creates a string with the command switches
     * a device from the TCP/IP connection mode
     * to the USB connection mode.
     * 
     * @param host Device host (IP).
     * @param port Device port.
     * 
     * @return The command to be used to switch back to USB connection mode.
     */
    private static String[] createSwitchToUSBConnectionModeCommand(String host, String port)
    {

        String hostPort = host + ":" + port; //$NON-NLS-1$

        String sdkPath = SdkUtils.getSdkPath();

        String cmd[] =
                {
                        sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                        DEVICE_ID_INDICATOR, hostPort, USB_SWITCH_BACK_COMMAND
                };

        return cmd;
    }

    /**
     * Creates a string with the command that should
     * be called in order to switch adb connection from USB to TPCIP mode
     * 
     * @param serialNumber device serial number
     * @param port device port
     * @return the command to be used to switch adb connection to TCPIP mode
     */
    private static String[] createSwitchToTcpIpCommand(String serialNumber, String port)
    {
        String sdkPath = SdkUtils.getSdkPath();

        String cmd[] =
                {
                        sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                        ADB_INSTANCE_PARAMETER, serialNumber, TCPIP_CMD, port
                };

        return cmd;
    }

    /**
     * Creates a string with the command that should
     * be called to delete a file from device
     * 
     * @param serialNumber
     * @param file
     * @param folder
     * @return
     */
    private static String[] createDeleteFileFromDeviceCommand(String serialNumber, String file,
            String folder)
    {
        String sdkPath = SdkUtils.getSdkPath();

        // The tools folder should exist and be here, but double-cheking
        // once more wont kill
        File f = new File(sdkPath + PLATFORM_TOOLS_FOLDER + File.separator);
        if (!f.exists())
        {
            StudioLogger
                    .error("Run: Could not find tools folder on " + sdkPath + PLATFORM_TOOLS_FOLDER //$NON-NLS-1$
                            + File.separator);
        }
        else
        {
            if (!f.isDirectory())
            {
                StudioLogger.error("Run: Invalid tools folder " + sdkPath + PLATFORM_TOOLS_FOLDER //$NON-NLS-1$
                        + File.separator);
            }
        }

        String cmd[] =
                {
                        sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                        ADB_INSTANCE_PARAMETER, serialNumber, SHELL_CMD,
                        "rm /" + folder + "/" + file //$NON-NLS-1$ //$NON-NLS-2$
                };

        return cmd;
    }

    /**
     * Uses the ADB shell command to remove a file from the device
     * 
     * @param serialNumber
     * @param fileName
     * @param sdCardFolder
     * @return
     * @throws IOException
     */
    private static boolean deleteFileFromDevice(String serialNumber, String fileName, String folder)
            throws IOException
    {

        String command[] = createDeleteFileFromDeviceCommand(serialNumber, fileName, folder);
        IStatus status = executeRemoteDevicesCommand(command, null, 1000, "", new IStopCondition() //$NON-NLS-1$
                {

                    public boolean canStop()
                    {
                        return true;
                    }
                }, null);

        return status.isOK();
    }

    /**
     * Check if a device identified by the serial number has a mounted SDCard
     * @param serialNumber the serial number
     * @return true if the device has a SDCard
     * @throws IOException 
     */
    public static boolean hasSDCard(String serialNumber) throws IOException
    {
        boolean hasSdCard = false;
        File tempSdCardFile = File.createTempFile("SDcheck", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
        boolean tempCopiedOnSdCardFile =
                pushFileToDevice(serialNumber, SDCARD_FOLDER, tempSdCardFile);

        if (tempCopiedOnSdCardFile)
        {
            //trying to write on /sdcard folder (it works for phones previous from Platform 2.2)
            if (!deleteFileFromDevice(serialNumber, tempSdCardFile.getName(), SDCARD_FOLDER))
            {
                StudioLogger
                        .error("DDMSFacade: Could not delete tempfile from /sdcard when checking if card is enabled"); //$NON-NLS-1$
            }
            hasSdCard = true;
            tempSdCardFile.delete();
        }
        else
        {

            File tempMntFile = File.createTempFile("SDcheck", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
            boolean tempCopiedOnMntFile =
                    pushFileToDevice(serialNumber, MNT_SDCARD_FOLDER, tempSdCardFile);

            if (tempCopiedOnMntFile)
            {
                //trying to write on /mnt/sdcard folder (it works for phones since Platform 2.2)
                if (!deleteFileFromDevice(serialNumber, tempMntFile.getName(), MNT_SDCARD_FOLDER))
                {
                    StudioLogger
                            .error("DDMSFacade: Could not delete tempfile from /mnt/sdcard when checking if card is enabled"); //$NON-NLS-1$
                }
                hasSdCard = true;
                tempMntFile.delete();
            }

        }

        return hasSdCard;
    }

    /**
     * 
     * @param serialNumber
     * @param sdCardFolder
     * @param tempFile
     * @return true if manages to push file into the folder specified on device
     */
    private static boolean pushFileToDevice(String serialNumber, String folder, File file)
    {
        Collection<String> files = new ArrayList<String>();
        files.add(file.getName());
        Path path = new Path(file.getAbsolutePath());

        IStatus status =
                pushFiles(serialNumber, path.removeLastSegments(1).toString(), files, folder, 2000,
                        new NullProgressMonitor(), null);

        return status.isOK();
    }

    /**
     * Creates a string with the command that should
     * be called in order to disconnect from an IP/Port
     * 
     * @param host device host (IP)
     * @param port device port
     * @return the command to be used to disconnect from an IP/Port
     */
    private static String[] createDisconnectTcpIpCommand(String host, String port)
    {

        String hostPort = host + ":" + port; //$NON-NLS-1$

        String sdkPath = SdkUtils.getSdkPath();
        String cmd[] =
                {
                        sdkPath + PLATFORM_TOOLS_FOLDER + File.separator + ADB_COMMAND,
                        DISCONNECT_TCPIP_CMD, hostPort
                };

        return cmd;
    }

    public static void deleteFile(String serialNumber, String path) throws IOException
    {
        DDMSFacade.execRemoteApp(serialNumber, "rm " + path, //$NON-NLS-1$
                new NullProgressMonitor());
    }
}