HelperUtils.java 12 KB

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