HelperUtils.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import java.net.InetAddress;
  3. import java.net.UnknownHostException;
  4. import java.security.KeyStore;
  5. import org.apache.http.HttpVersion;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.conn.ClientConnectionManager;
  9. import org.apache.http.conn.scheme.PlainSocketFactory;
  10. import org.apache.http.conn.scheme.Scheme;
  11. import org.apache.http.conn.scheme.SchemeRegistry;
  12. import org.apache.http.conn.ssl.SSLSocketFactory;
  13. import org.apache.http.entity.StringEntity;
  14. import org.apache.http.impl.client.DefaultHttpClient;
  15. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  16. import org.apache.http.params.BasicHttpParams;
  17. import org.apache.http.params.HttpParams;
  18. import org.apache.http.params.HttpProtocolParams;
  19. import org.apache.http.protocol.HTTP;
  20. import de.tudarmstadt.informatik.hostage.logging.Record;
  21. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  22. import android.content.Context;
  23. import android.net.ConnectivityManager;
  24. import android.net.NetworkInfo;
  25. import android.net.wifi.WifiInfo;
  26. import android.net.wifi.WifiManager;
  27. import android.os.Environment;
  28. import android.preference.PreferenceManager;
  29. import android.text.TextUtils;
  30. /**
  31. * Helper class with some static methods for general usage.
  32. * @author Lars Pandikow
  33. * @author Wulf Pfeiffer
  34. *
  35. */
  36. public final class HelperUtils {
  37. /**
  38. * Gets SSID of the wireless network.
  39. * @param context Needs a context to get system recourses
  40. * @return SSID of wireless network if connected, else null.
  41. */
  42. public static String getSSID(Context context) {
  43. String ssid = null;
  44. ConnectivityManager connManager = (ConnectivityManager) context
  45. .getSystemService(Context.CONNECTIVITY_SERVICE);
  46. NetworkInfo networkInfo = connManager
  47. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  48. if (networkInfo != null && networkInfo.isConnected()) {
  49. final WifiManager wifiManager = (WifiManager) context
  50. .getSystemService(Context.WIFI_SERVICE);
  51. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  52. if (connectionInfo != null
  53. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  54. ssid = connectionInfo.getSSID();
  55. }
  56. }
  57. return ssid;
  58. }
  59. /**
  60. * Gets BSSID of the wireless network.
  61. * @param context Needs a context to get system recourses.
  62. * @return BSSID of wireless network if connected, else null.
  63. */
  64. public static String getBSSID(Context context) {
  65. String bssid = null;
  66. ConnectivityManager connManager = (ConnectivityManager) context
  67. .getSystemService(Context.CONNECTIVITY_SERVICE);
  68. NetworkInfo networkInfo = connManager
  69. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  70. if (networkInfo != null && networkInfo.isConnected()) {
  71. final WifiManager wifiManager = (WifiManager) context
  72. .getSystemService(Context.WIFI_SERVICE);
  73. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  74. if (connectionInfo != null
  75. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  76. bssid = connectionInfo.getBSSID();
  77. }
  78. }
  79. return bssid;
  80. }
  81. /**
  82. * Gets internal IP address of the device in a wireless network.
  83. * @param context Needs a context to get system recourses.
  84. * @return internal IP of the device in a wireless network if connected, else null.
  85. */
  86. public static String getInternalIP(Context context) {
  87. String ipAddress = null;
  88. ConnectivityManager connManager = (ConnectivityManager) context
  89. .getSystemService(Context.CONNECTIVITY_SERVICE);
  90. NetworkInfo networkInfo = connManager
  91. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  92. if (networkInfo != null && networkInfo.isConnected()) {
  93. final WifiManager wifiManager = (WifiManager) context
  94. .getSystemService(Context.WIFI_SERVICE);
  95. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  96. if (connectionInfo != null) {
  97. try {
  98. ipAddress = InetAddress.getByAddress(
  99. unpackInetAddress(connectionInfo.getIpAddress()))
  100. .getHostAddress();
  101. } catch (UnknownHostException e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. }
  106. return ipAddress;
  107. }
  108. private static byte[] unpackInetAddress(int bytes) {
  109. return new byte[] { (byte) ((bytes) & 0xff),
  110. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  111. (byte) ((bytes >>> 24) & 0xff) };
  112. }
  113. /**
  114. * Checks if external storage is available for read and write.
  115. * @return True if external storage is available for read and write, else false.
  116. */
  117. public static boolean isExternalStorageWritable() {
  118. String state = Environment.getExternalStorageState();
  119. if (Environment.MEDIA_MOUNTED.equals(state)) {
  120. return true;
  121. }
  122. return false;
  123. }
  124. /**
  125. * Creates a HttpClient with an own SSL Socket.
  126. * @return HttpsClient who accepts accepts all certificates.
  127. * @see MySSLSocketFactory
  128. */
  129. public static HttpClient createHttpClient() {
  130. try {
  131. KeyStore trustStore = KeyStore.getInstance(KeyStore
  132. .getDefaultType());
  133. trustStore.load(null, null);
  134. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  135. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  136. HttpParams params = new BasicHttpParams();
  137. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  138. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  139. SchemeRegistry registry = new SchemeRegistry();
  140. registry.register(new Scheme("http", PlainSocketFactory
  141. .getSocketFactory(), 80));
  142. registry.register(new Scheme("https", sf, 443));
  143. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  144. params, registry);
  145. return new DefaultHttpClient(ccm, params);
  146. } catch (Exception e) {
  147. e.printStackTrace();
  148. return new DefaultHttpClient();
  149. }
  150. }
  151. /**
  152. * Uploads a single Record to a server, specified in the settings.
  153. * @param record The Record to upload.
  154. * @return True if the upload was successful, else false.
  155. */
  156. public static boolean uploadSingleRecord(Context context, Record record){
  157. // Create a https client. Uses MySSLSocketFactory to accept all certificates
  158. HttpClient httpclient = HelperUtils.createHttpClient();
  159. HttpPost httppost;
  160. try {
  161. // Create HttpPost
  162. httppost = new HttpPost(PreferenceManager.getDefaultSharedPreferences(context).getString("pref_upload", "https://ssi.cased.de"));
  163. // Create JSON String of Record
  164. StringEntity se = new StringEntity(record.toString(0x01));
  165. httppost.setEntity(se);
  166. // Execute HttpPost
  167. httpclient.execute(httppost);
  168. } catch (Exception e) {
  169. e.printStackTrace();
  170. return false;
  171. }
  172. return true;
  173. }
  174. /**
  175. * Concatenates several byte arrays.
  176. * @param bytes The byte arrays.
  177. * @return A single byte arrays containing all the bytes from the given arrays in the order they are given.
  178. */
  179. public static byte[] concat(byte[]... bytes) {
  180. int newSize = 0;
  181. for (byte[] b : bytes)
  182. if(b != null) newSize += b.length;
  183. byte[] dst = new byte[newSize];
  184. int currentPos = 0;
  185. int newPos;
  186. for (byte[] b : bytes) {
  187. if(b != null) {
  188. newPos = b.length;
  189. System.arraycopy(b, 0, dst, currentPos, newPos);
  190. currentPos += newPos;
  191. }
  192. }
  193. return dst;
  194. }
  195. /**
  196. * Converts a byte[] to a String, but only characters in ASCII between 32 and 127
  197. * @param bytes that are converted
  198. * @return converted String
  199. */
  200. public static String byteToStr(byte[] bytes) {
  201. char[] chars = new char[bytes.length];
  202. for (int i = 0, j = 0; i < bytes.length && j < chars.length; i++) {
  203. if (isLetter((char) bytes[i])) {
  204. chars[j] = (char) bytes[i];
  205. j++;
  206. }
  207. }
  208. return new String(chars);
  209. }
  210. /**
  211. * Determines if a character is in ASCII between 32 and 126
  212. * @param character that is checked
  213. * @return true if the character is between 32 and 126, else false
  214. */
  215. private static boolean isLetter(char character) {
  216. return (character > 31 && character < 127);
  217. }
  218. /**
  219. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to "00, 01".
  220. * @param bytes that will be converted.
  221. * @return converted String.
  222. */
  223. public static String bytesToHexString(byte[] bytes) {
  224. char[] hexArray = "0123456789ABCDEF".toCharArray();
  225. int v;
  226. StringBuffer buffer = new StringBuffer();
  227. for(int j = 0; j < bytes.length; j++ ) {
  228. v = bytes[j] & 0xFF;
  229. buffer.append(hexArray[v >>> 4]);
  230. buffer.append(hexArray[v & 0x0F]);
  231. if(j < bytes.length-1) buffer.append(", ");
  232. }
  233. return buffer.toString();
  234. }
  235. /**
  236. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  237. * @param string that will be converted.
  238. * @return converted byte array.
  239. */
  240. public static byte[] hexStringToBytes(String string) {
  241. String[] hexStrings = string.split(", ");
  242. byte[] bytes = new byte[hexStrings.length];
  243. for(int j = 0; j < hexStrings.length; j++ ) {
  244. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4)
  245. + Character.digit(hexStrings[j].charAt(1), 16));
  246. }
  247. return bytes;
  248. }
  249. }