HelperUtils.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.InetAddress;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7. import java.security.KeyStore;
  8. import java.security.SecureRandom;
  9. import org.apache.http.HttpEntity;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.HttpVersion;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.conn.ClientConnectionManager;
  16. import org.apache.http.conn.scheme.PlainSocketFactory;
  17. import org.apache.http.conn.scheme.Scheme;
  18. import org.apache.http.conn.scheme.SchemeRegistry;
  19. import org.apache.http.conn.ssl.SSLSocketFactory;
  20. import org.apache.http.entity.StringEntity;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  23. import org.apache.http.params.BasicHttpParams;
  24. import org.apache.http.params.HttpParams;
  25. import org.apache.http.params.HttpProtocolParams;
  26. import org.apache.http.protocol.HTTP;
  27. import org.apache.http.util.EntityUtils;
  28. import org.json.JSONObject;
  29. import de.tudarmstadt.informatik.hostage.R;
  30. import de.tudarmstadt.informatik.hostage.logging.Record;
  31. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  32. import de.tudarmstadt.informatik.hostage.ui.MainActivity;
  33. import android.content.Context;
  34. import android.net.ConnectivityManager;
  35. import android.net.NetworkInfo;
  36. import android.net.wifi.WifiInfo;
  37. import android.net.wifi.WifiManager;
  38. import android.os.AsyncTask;
  39. import android.os.Environment;
  40. import android.preference.PreferenceManager;
  41. import android.text.TextUtils;
  42. import android.widget.TextView;
  43. /**
  44. * Helper class with some static methods for general usage.
  45. * @author Lars Pandikow
  46. * @author Wulf Pfeiffer
  47. *
  48. */
  49. public final class HelperUtils {
  50. /**
  51. * Gets SSID of the wireless network.
  52. * @param context Needs a context to get system recourses
  53. * @return SSID of wireless network if connected, else null.
  54. */
  55. public static String getSSID(Context context) {
  56. String ssid = null;
  57. ConnectivityManager connManager = (ConnectivityManager) context
  58. .getSystemService(Context.CONNECTIVITY_SERVICE);
  59. NetworkInfo networkInfo = connManager
  60. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  61. if (networkInfo != null && networkInfo.isConnected()) {
  62. final WifiManager wifiManager = (WifiManager) context
  63. .getSystemService(Context.WIFI_SERVICE);
  64. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  65. if (connectionInfo != null
  66. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  67. ssid = connectionInfo.getSSID();
  68. }
  69. }
  70. return ssid;
  71. }
  72. /**
  73. * Gets BSSID of the wireless network.
  74. * @param context Needs a context to get system recourses.
  75. * @return BSSID of wireless network if connected, else null.
  76. */
  77. public static String getBSSID(Context context) {
  78. String bssid = null;
  79. ConnectivityManager connManager = (ConnectivityManager) context
  80. .getSystemService(Context.CONNECTIVITY_SERVICE);
  81. NetworkInfo networkInfo = connManager
  82. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  83. if (networkInfo != null && networkInfo.isConnected()) {
  84. final WifiManager wifiManager = (WifiManager) context
  85. .getSystemService(Context.WIFI_SERVICE);
  86. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  87. if (connectionInfo != null
  88. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  89. bssid = connectionInfo.getBSSID();
  90. }
  91. }
  92. return bssid;
  93. }
  94. /**
  95. * Gets internal IP address of the device in a wireless network.
  96. * @param context Needs a context to get system recourses.
  97. * @return internal IP of the device in a wireless network if connected, else null.
  98. */
  99. public static String getInternalIP(Context context) {
  100. String ipAddress = null;
  101. ConnectivityManager connManager = (ConnectivityManager) context
  102. .getSystemService(Context.CONNECTIVITY_SERVICE);
  103. NetworkInfo networkInfo = connManager
  104. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  105. if (networkInfo != null && networkInfo.isConnected()) {
  106. final WifiManager wifiManager = (WifiManager) context
  107. .getSystemService(Context.WIFI_SERVICE);
  108. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  109. if (connectionInfo != null) {
  110. try {
  111. ipAddress = InetAddress.getByAddress(
  112. unpackInetAddress(connectionInfo.getIpAddress()))
  113. .getHostAddress();
  114. } catch (UnknownHostException e) {
  115. e.printStackTrace();
  116. }
  117. }
  118. }
  119. return ipAddress;
  120. }
  121. private static byte[] unpackInetAddress(int bytes) {
  122. return new byte[] { (byte) ((bytes) & 0xff),
  123. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  124. (byte) ((bytes >>> 24) & 0xff) };
  125. }
  126. /**
  127. * Checks if external storage is available for read and write.
  128. * @return True if external storage is available for read and write, else false.
  129. */
  130. public static boolean isExternalStorageWritable() {
  131. String state = Environment.getExternalStorageState();
  132. if (Environment.MEDIA_MOUNTED.equals(state)) {
  133. return true;
  134. }
  135. return false;
  136. }
  137. /**
  138. * Creates a HttpClient with an own SSL Socket.
  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. * @param record The Record to upload.
  167. * @return True if the upload was successful, else false.
  168. */
  169. public static boolean uploadSingleRecord(Context context, Record record){
  170. // Create a https client. Uses MySSLSocketFactory to accept all certificates
  171. HttpClient httpclient = HelperUtils.createHttpClient();
  172. HttpPost httppost;
  173. try {
  174. // Create HttpPost
  175. httppost = new HttpPost(PreferenceManager.getDefaultSharedPreferences(context).getString("pref_upload", "https://ssi.cased.de"));
  176. // Create JSON String of Record
  177. StringEntity se = new StringEntity(record.toString(0x01));
  178. httppost.setEntity(se);
  179. // Execute HttpPost
  180. httpclient.execute(httppost);
  181. } catch (Exception e) {
  182. e.printStackTrace();
  183. return false;
  184. }
  185. return true;
  186. }
  187. /**
  188. * Concatenates several byte arrays.
  189. * @param bytes The byte arrays.
  190. * @return A single byte arrays containing all the bytes from the given arrays in the order they are given.
  191. */
  192. public static byte[] concat(byte[]... bytes) {
  193. int newSize = 0;
  194. for (byte[] b : bytes)
  195. if(b != null) newSize += b.length;
  196. byte[] dst = new byte[newSize];
  197. int currentPos = 0;
  198. int newPos;
  199. for (byte[] b : bytes) {
  200. if(b != null) {
  201. newPos = b.length;
  202. System.arraycopy(b, 0, dst, currentPos, newPos);
  203. currentPos += newPos;
  204. }
  205. }
  206. return dst;
  207. }
  208. /**
  209. * Converts a byte[] to a String, but only characters in ASCII between 32 and 127
  210. * @param bytes that are converted
  211. * @return converted String
  212. */
  213. public static String byteToStr(byte[] bytes) {
  214. char[] chars = new char[bytes.length];
  215. for (int i = 0, j = 0; i < bytes.length && j < chars.length; i++) {
  216. if (isLetter((char) bytes[i])) {
  217. chars[j] = (char) bytes[i];
  218. j++;
  219. }
  220. }
  221. return new String(chars);
  222. }
  223. /**
  224. * Determines if a character is in ASCII between 32 and 126
  225. * @param character that is checked
  226. * @return true if the character is between 32 and 126, else false
  227. */
  228. private static boolean isLetter(char character) {
  229. return (character > 31 && character < 127);
  230. }
  231. /**
  232. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to "00, 01".
  233. * @param bytes that will be converted.
  234. * @return converted String.
  235. */
  236. public static String bytesToHexString(byte[] bytes) {
  237. char[] hexArray = "0123456789ABCDEF".toCharArray();
  238. int v;
  239. StringBuffer buffer = new StringBuffer();
  240. for(int j = 0; j < bytes.length; j++ ) {
  241. v = bytes[j] & 0xFF;
  242. buffer.append(hexArray[v >>> 4]);
  243. buffer.append(hexArray[v & 0x0F]);
  244. if(j < bytes.length-1) buffer.append(", ");
  245. }
  246. return buffer.toString();
  247. }
  248. /**
  249. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  250. * @param string that will be converted.
  251. * @return converted byte array.
  252. */
  253. public static byte[] hexStringToBytes(String string) {
  254. String[] hexStrings = string.split(", ");
  255. byte[] bytes = new byte[hexStrings.length];
  256. for(int j = 0; j < hexStrings.length; j++ ) {
  257. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4)
  258. + Character.digit(hexStrings[j].charAt(1), 16));
  259. }
  260. return bytes;
  261. }
  262. private static String qotd;
  263. /**
  264. * qotd getter.
  265. * @return qotd
  266. */
  267. public static String getQotd() {
  268. return qotd;
  269. }
  270. /**
  271. * qotd setter.
  272. * If qotd is null (this means something went wrong with getting a qotd from server),
  273. * a random string is generated instead.
  274. * @param newQotd
  275. */
  276. public static void setQotd(String newQotd) {
  277. qotd = newQotd;
  278. if(newQotd == null) {
  279. SecureRandom rndm = new SecureRandom();
  280. char[] c = new char[rndm.nextInt(100)];
  281. for(int i = 0; i < c.length; i++) {
  282. c[i] = (char) (rndm.nextInt(95)+32);
  283. }
  284. qotd = new String(c);
  285. }
  286. }
  287. }