HelperUtils.java 11 KB

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