HelperUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import org.apache.http.HttpVersion;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.methods.HttpPost;
  5. import org.apache.http.conn.ClientConnectionManager;
  6. import org.apache.http.conn.scheme.PlainSocketFactory;
  7. import org.apache.http.conn.scheme.Scheme;
  8. import org.apache.http.conn.scheme.SchemeRegistry;
  9. import org.apache.http.conn.ssl.SSLSocketFactory;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  13. import org.apache.http.params.BasicHttpParams;
  14. import org.apache.http.params.HttpParams;
  15. import org.apache.http.params.HttpProtocolParams;
  16. import org.apache.http.protocol.HTTP;
  17. import java.net.InetAddress;
  18. import java.net.UnknownHostException;
  19. import java.security.KeyStore;
  20. import java.security.SecureRandom;
  21. import android.content.Context;
  22. import android.net.ConnectivityManager;
  23. import android.net.NetworkInfo;
  24. import android.net.wifi.WifiInfo;
  25. import android.net.wifi.WifiManager;
  26. import android.os.Environment;
  27. import android.preference.PreferenceManager;
  28. import android.text.TextUtils;
  29. import de.tudarmstadt.informatik.hostage.logging.Record;
  30. import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
  31. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  32. /**
  33. * Helper class with some static methods for general usage.
  34. *
  35. * @author Lars Pandikow
  36. * @author Wulf Pfeiffer
  37. *
  38. */
  39. public final class HelperUtils {
  40. /**
  41. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
  42. * "00, 01".
  43. *
  44. * @param bytes
  45. * that will be converted.
  46. * @return converted String.
  47. */
  48. public static String bytesToHexString(byte[] bytes) {
  49. char[] hexArray = "0123456789ABCDEF".toCharArray();
  50. int v;
  51. StringBuffer buffer = new StringBuffer();
  52. for (int j = 0; j < bytes.length; j++) {
  53. v = bytes[j] & 0xFF;
  54. buffer.append(hexArray[v >>> 4]);
  55. buffer.append(hexArray[v & 0x0F]);
  56. if (j < bytes.length - 1)
  57. buffer.append(", ");
  58. }
  59. return buffer.toString();
  60. }
  61. /**
  62. * Converts a byte[] to a String, but only characters in ASCII between 32
  63. * and 127
  64. *
  65. * @param bytes
  66. * that are converted
  67. * @return converted String
  68. */
  69. public static String byteToStr(byte[] bytes) {
  70. int size = 0;
  71. for(byte b : bytes) {
  72. if(isLetter((char) b)) {
  73. size++;
  74. }
  75. }
  76. char[] chars = new char[size];
  77. for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
  78. if (isLetter((char) bytes[i])) {
  79. chars[j] = (char) bytes[i];
  80. j++;
  81. }
  82. }
  83. return new String(chars);
  84. }
  85. /**
  86. * Concatenates several byte arrays.
  87. *
  88. * @param bytes
  89. * The byte arrays.
  90. * @return A single byte arrays containing all the bytes from the given
  91. * arrays in the order they are given.
  92. */
  93. public static byte[] concat(byte[]... bytes) {
  94. int newSize = 0;
  95. for (byte[] b : bytes)
  96. if (b != null)
  97. newSize += b.length;
  98. byte[] dst = new byte[newSize];
  99. int currentPos = 0;
  100. int newPos;
  101. for (byte[] b : bytes) {
  102. if (b != null) {
  103. newPos = b.length;
  104. System.arraycopy(b, 0, dst, currentPos, newPos);
  105. currentPos += newPos;
  106. }
  107. }
  108. return dst;
  109. }
  110. /**
  111. * Puts a 0x00 byte between each byte in a byte array.
  112. *
  113. * @param bytes
  114. * that need to be filled with 0x00.
  115. * @return filled byte array.
  116. */
  117. public static byte[] fillWithZero(byte[] bytes) {
  118. byte[] newBytes = new byte[(bytes.length * 2)];
  119. for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
  120. newBytes[j] = bytes[i];
  121. newBytes[j + 1] = 0x00;
  122. }
  123. return newBytes;
  124. }
  125. /**
  126. * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
  127. * a byte array.
  128. *
  129. * @param bytes
  130. * that need to be filled with 0x00.
  131. * @return filled byte array.
  132. */
  133. public static byte[] fillWithZeroExtended(byte[] bytes) {
  134. byte[] zeroBytes = fillWithZero(bytes);
  135. byte[] newBytes = new byte[zeroBytes.length + 2];
  136. newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
  137. return newBytes;
  138. }
  139. /**
  140. * Gets BSSID of the wireless network.
  141. *
  142. * @param context
  143. * Needs a context to get system recourses.
  144. * @return BSSID of wireless network if connected, else null.
  145. */
  146. public static String getBSSID(Context context) {
  147. String bssid = null;
  148. ConnectivityManager connManager = (ConnectivityManager) context
  149. .getSystemService(Context.CONNECTIVITY_SERVICE);
  150. NetworkInfo networkInfo = connManager
  151. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  152. if (networkInfo != null && networkInfo.isConnected()) {
  153. final WifiManager wifiManager = (WifiManager) context
  154. .getSystemService(Context.WIFI_SERVICE);
  155. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  156. if (connectionInfo != null
  157. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  158. bssid = connectionInfo.getBSSID();
  159. }
  160. }
  161. return bssid;
  162. }
  163. public static HttpClient createHttpClient() {
  164. try {
  165. KeyStore trustStore = KeyStore.getInstance(KeyStore
  166. .getDefaultType());
  167. trustStore.load(null, null);
  168. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  169. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  170. HttpParams params = new BasicHttpParams();
  171. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  172. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  173. SchemeRegistry registry = new SchemeRegistry();
  174. registry.register(new Scheme("http", PlainSocketFactory
  175. .getSocketFactory(), 80));
  176. registry.register(new Scheme("https", sf, 443));
  177. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  178. params, registry);
  179. return new DefaultHttpClient(ccm, params);
  180. } catch (Exception e) {
  181. e.printStackTrace();
  182. return new DefaultHttpClient();
  183. }
  184. }
  185. public static boolean uploadSingleRecord(Context context, Record record) {
  186. // Create a https client. Uses MySSLSocketFactory to accept all
  187. // certificates
  188. HttpClient httpclient = HelperUtils.createHttpClient();
  189. HttpPost httppost;
  190. try {
  191. // Create HttpPost
  192. httppost = new HttpPost(PreferenceManager
  193. .getDefaultSharedPreferences(context).getString(
  194. "pref_upload", "https://ssi.cased.de"));
  195. // Create JSON String of Record
  196. StringEntity se = new StringEntity(record.toString(TraCINgFormatter.getInstance()));
  197. httppost.setEntity(se);
  198. // Execute HttpPost
  199. httpclient.execute(httppost);
  200. } catch (Exception e) {
  201. e.printStackTrace();
  202. return false;
  203. }
  204. return true;
  205. }
  206. /**
  207. * Gets internal IP address of the device in a wireless network.
  208. *
  209. * @param context
  210. * Needs a context to get system recourses.
  211. * @return internal IP of the device in a wireless network if connected,
  212. * else null.
  213. */
  214. public static String getInternalIP(Context context) {
  215. String ipAddress = null;
  216. ConnectivityManager connManager = (ConnectivityManager) context
  217. .getSystemService(Context.CONNECTIVITY_SERVICE);
  218. NetworkInfo networkInfo = connManager
  219. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  220. if (networkInfo != null && networkInfo.isConnected()) {
  221. final WifiManager wifiManager = (WifiManager) context
  222. .getSystemService(Context.WIFI_SERVICE);
  223. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  224. if (connectionInfo != null) {
  225. try {
  226. ipAddress = InetAddress.getByAddress(
  227. unpackInetAddress(connectionInfo.getIpAddress()))
  228. .getHostAddress();
  229. } catch (UnknownHostException e) {
  230. e.printStackTrace();
  231. }
  232. }
  233. }
  234. return ipAddress;
  235. }
  236. /**
  237. * Gets SSID of the wireless network.
  238. *
  239. * @param context
  240. * Needs a context to get system recourses
  241. * @return SSID of wireless network if connected, else null.
  242. */
  243. public static String getSSID(Context context) {
  244. String ssid = null;
  245. ConnectivityManager connManager = (ConnectivityManager) context
  246. .getSystemService(Context.CONNECTIVITY_SERVICE);
  247. NetworkInfo networkInfo = connManager
  248. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  249. if (networkInfo != null && networkInfo.isConnected()) {
  250. final WifiManager wifiManager = (WifiManager) context
  251. .getSystemService(Context.WIFI_SERVICE);
  252. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  253. if (connectionInfo != null
  254. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  255. ssid = connectionInfo.getSSID();
  256. }
  257. }
  258. return ssid;
  259. }
  260. /**
  261. * Gets the mac address of the devicek.
  262. *
  263. * @param context
  264. * Needs a context to get system recourses
  265. * @return MAC address of the device.
  266. */
  267. public static String getMacAdress(Context context) {
  268. String mac = null;
  269. WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  270. WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  271. mac = connectionInfo.getMacAddress();
  272. return mac;
  273. }
  274. /**
  275. * Produces a random String. The String can be of random length (minimum 1)
  276. * with a maximum length, or it can be forced to have the length that was
  277. * given.
  278. *
  279. * @param length
  280. * maximal / forced length of String.
  281. * @param forceLength
  282. * forces the String to be exact the given length instead of
  283. * maximum
  284. * @return random String.
  285. */
  286. public static String getRandomString(int length, boolean forceLength) {
  287. SecureRandom rndm = new SecureRandom();
  288. char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
  289. for (int i = 0; i < c.length; i++) {
  290. c[i] = (char) (rndm.nextInt(95) + 32);
  291. }
  292. return new String(c);
  293. }
  294. /**
  295. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  296. *
  297. * @param string
  298. * that will be converted.
  299. * @return converted byte array.
  300. */
  301. public static byte[] hexStringToBytes(String string) {
  302. String[] hexStrings = string.split(", ");
  303. byte[] bytes = new byte[hexStrings.length];
  304. for (int j = 0; j < hexStrings.length; j++) {
  305. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
  306. .digit(hexStrings[j].charAt(1), 16));
  307. }
  308. return bytes;
  309. }
  310. /**
  311. * Generates a random byte[] of a specified size
  312. *
  313. * @param size
  314. * of the byte[]
  315. * @return random byte[]
  316. */
  317. public static byte[] randomBytes(int size) {
  318. byte[] bytes = new byte[size];
  319. SecureRandom rdm = new SecureRandom();
  320. rdm.nextBytes(bytes);
  321. return bytes;
  322. }
  323. /**
  324. * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
  325. * {0x02, 0x01, 0x00}.
  326. *
  327. * @param bytes
  328. * array that is turned.
  329. * @return turned array.
  330. */
  331. public static byte[] turnByteArray(byte[] bytes) {
  332. byte[] tmp = new byte[bytes.length];
  333. for (int i = 0; i < bytes.length; i++) {
  334. tmp[i] = bytes[bytes.length - 1 - i];
  335. }
  336. return tmp;
  337. }
  338. /**
  339. * Determines if a character is in ASCII between 32 and 126
  340. *
  341. * @param character
  342. * that is checked
  343. * @return true if the character is between 32 and 126, else false
  344. */
  345. private static boolean isLetter(char character) {
  346. return (character > 31 && character < 127);
  347. }
  348. private static byte[] unpackInetAddress(int bytes) {
  349. return new byte[] { (byte) ((bytes) & 0xff),
  350. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  351. (byte) ((bytes >>> 24) & 0xff) };
  352. }
  353. public static boolean isWifiConnected(Context context){
  354. if(context == null) return false;
  355. ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  356. NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  357. return mWifi.isConnected();
  358. }
  359. public static boolean isNetworkAvailable(Context context) {
  360. if(context == null) return false;
  361. ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  362. NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  363. return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  364. }
  365. }