RecordOverviewFragment.java 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. package de.tudarmstadt.informatik.hostage.ui.fragment;
  2. import android.annotation.SuppressLint;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.app.FragmentManager;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.content.SharedPreferences;
  12. import android.os.Bundle;
  13. import android.preference.PreferenceManager;
  14. import android.support.v4.content.LocalBroadcastManager;
  15. import android.util.Log;
  16. import android.view.LayoutInflater;
  17. import android.view.Menu;
  18. import android.view.MenuInflater;
  19. import android.view.MenuItem;
  20. import android.view.View;
  21. import android.view.ViewGroup;
  22. import android.widget.ExpandableListView;
  23. import android.widget.ImageButton;
  24. import android.widget.ProgressBar;
  25. import android.widget.Toast;
  26. import com.google.android.gms.maps.model.LatLng;
  27. import java.text.DateFormat;
  28. import java.text.SimpleDateFormat;
  29. import java.util.ArrayList;
  30. import java.util.Calendar;
  31. import java.util.Collections;
  32. import java.util.Comparator;
  33. import java.util.Date;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Locale;
  37. import java.util.Random;
  38. import de.tudarmstadt.informatik.hostage.Handler;
  39. import de.tudarmstadt.informatik.hostage.Hostage;
  40. import de.tudarmstadt.informatik.hostage.R;
  41. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  42. import de.tudarmstadt.informatik.hostage.logging.LogExport;
  43. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  44. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  45. import de.tudarmstadt.informatik.hostage.logging.Record;
  46. import de.tudarmstadt.informatik.hostage.logging.SyncData;
  47. import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
  48. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  49. import de.tudarmstadt.informatik.hostage.sync.android.SyncUtils;
  50. import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
  51. import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSyncActivity;
  52. import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
  53. import de.tudarmstadt.informatik.hostage.sync.wifi_direct.ui.WiFiP2pSyncActivity;
  54. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  55. import de.tudarmstadt.informatik.hostage.ui.adapter.RecordListAdapter;
  56. import de.tudarmstadt.informatik.hostage.ui.dialog.ChecklistDialog;
  57. import de.tudarmstadt.informatik.hostage.ui.dialog.DateTimeDialogFragment;
  58. import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
  59. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  60. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter.SortType;
  61. import de.tudarmstadt.informatik.hostage.ui.model.ServicesListItem;
  62. import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopup;
  63. import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopupItem;
  64. import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupItem;
  65. import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupTable;
  66. import de.tudarmstadt.informatik.hostage.ui.popup.SplitPopupItem;
  67. public class RecordOverviewFragment extends UpNavigatibleFragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
  68. static final String FILTER_MENU_TITLE_BSSID = MainActivity.getContext().getString(R.string.BSSID);
  69. static final String FILTER_MENU_TITLE_ESSID = MainActivity.getContext().getString(R.string.ESSID);
  70. static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.rec_protocol);
  71. static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(
  72. R.string.rec_latest);
  73. static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(
  74. R.string.rec_earliest);
  75. static final String FILTER_MENU_TITLE_SORTING = MainActivity.getContext().getString(R.string.rec_sortby);
  76. static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
  77. static final String FILTER_MENU_TITLE_GROUP = MainActivity.getContext().getString(
  78. R.string.rec_group_by);
  79. static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(
  80. R.string.rec_filter_by);
  81. static final int DEFAULT_GROUPING_KEY_INDEX = 0;
  82. private Hostage service;
  83. private boolean wasBelowTimePicker;
  84. private LogFilter filter;
  85. private boolean showFilterButton;
  86. private View rootView;
  87. private int mListPosition = -1;
  88. private int mItemPosition = -1;
  89. public String groupingKey;
  90. private ExpandableListView expListView;
  91. private ProgressBar spinner;
  92. private Toast noDataNotificationToast;
  93. HostageDBOpenHelper dbh;
  94. private String sectionToOpen = "";
  95. private ArrayList<Integer> openSections;
  96. private SharedPreferences pref;
  97. Thread loader;
  98. private boolean mReceiverRegistered = false;
  99. private BroadcastReceiver mReceiver;
  100. /* DATE CONVERSION STUFF*/
  101. static final DateFormat localisedDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
  102. // DATE WHICH PATTERN
  103. static final String localDatePattern = ((SimpleDateFormat)localisedDateFormatter).toLocalizedPattern();
  104. static final String groupingDatePattern = "MMMM yyyy";
  105. // INSERT HERE YOUR DATE PATERN
  106. static final SimpleDateFormat groupingDateFormatter = new SimpleDateFormat(groupingDatePattern);
  107. static final Calendar calendar = Calendar.getInstance();
  108. // DATE STRINGS
  109. static final String TODAY = MainActivity.getInstance().getResources().getString( R.string.TODAY);
  110. static final String YESTERDAY = MainActivity.getInstance().getResources().getString( R.string.YESTERDAY);
  111. private SyncInfo si ;// = s.getSyncInfo();
  112. private SyncData sd ;//= s.getSyncData(si);
  113. /**
  114. * Constructor
  115. */
  116. public RecordOverviewFragment(){}
  117. @Override
  118. public void onCreate(Bundle savedInstanceState) {
  119. super.onCreate(savedInstanceState);
  120. setHasOptionsMenu(true);
  121. }
  122. @Override
  123. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  124. Bundle savedInstanceState) {
  125. setHasOptionsMenu(true);
  126. getActivity().setTitle(getResources().getString(R.string.drawer_records));
  127. dbh = new HostageDBOpenHelper(this.getActivity().getBaseContext());
  128. pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
  129. // Get the message from the intent
  130. //this.addRecordToDB(4,4,4);
  131. /*
  132. Synchronizer s = new Synchronizer(this.dbh);
  133. si = s.getSyncInfo();
  134. HashMap<String, Long> map = new HashMap<String, Long>();
  135. map.put(SyncDevice.currentDevice().getDeviceID(), new Long(-1));
  136. si.deviceMap = map;
  137. sd = s.getSyncData(si);
  138. s.updateFromSyncData(sd);
  139. */
  140. if (this.filter == null){
  141. Intent intent = this.getActivity().getIntent();
  142. LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
  143. if(filter == null){
  144. this.clearFilter();
  145. } else {
  146. this.filter = filter;
  147. }
  148. }
  149. if (this.groupingKey == null) this.groupingKey = this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX);
  150. this.setShowFilterButton(!this.filter.isNotEditable());
  151. View rootView = inflater.inflate(this.getLayoutId(), container, false);
  152. this.rootView = rootView;
  153. ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
  154. this.spinner =(ProgressBar) rootView.findViewById(R.id.progressBar1);
  155. this.spinner.setVisibility(View.GONE);
  156. this.expListView = mylist;
  157. this.initialiseListView();
  158. ImageButton deleteButton = (ImageButton) rootView.findViewById(R.id.DeleteButton);
  159. deleteButton.setOnClickListener(new View.OnClickListener() {
  160. public void onClick(View v) {
  161. RecordOverviewFragment.this.openDeleteFilteredAttacksDialog();
  162. }
  163. });
  164. deleteButton.setVisibility(this.showFilterButton? View.VISIBLE : View.INVISIBLE);
  165. ImageButton filterButton = (ImageButton) rootView.findViewById(R.id.FilterButton);
  166. filterButton.setOnClickListener(new View.OnClickListener() {
  167. public void onClick(View v) {
  168. RecordOverviewFragment.this.openFilterPopupMenuOnView(v);
  169. }
  170. });
  171. filterButton.setVisibility(this.showFilterButton? View.VISIBLE : View.INVISIBLE);
  172. ImageButton sortButton = (ImageButton) rootView.findViewById(R.id.SortButton);
  173. sortButton.setOnClickListener(new View.OnClickListener() {
  174. public void onClick(View v) {
  175. // Open SortMenu
  176. RecordOverviewFragment.this.openSortingDialog();
  177. }
  178. });
  179. ImageButton groupButton = (ImageButton) rootView.findViewById(R.id.GroupButton);
  180. groupButton.setOnClickListener(new View.OnClickListener() {
  181. public void onClick(View v) {
  182. // Open SortMenu
  183. RecordOverviewFragment.this.openGroupingDialog();
  184. }
  185. });
  186. this.registerBroadcastReceiver();
  187. return rootView;
  188. }
  189. /**Initialises the expandable list view in a backgorund thread*/
  190. private void initialiseListView(){
  191. if (loader != null) loader.interrupt();
  192. this.spinner.setVisibility(View.VISIBLE);
  193. loader = new Thread(new Runnable(){
  194. private void updateUI(final RecordListAdapter currentAdapter)
  195. {
  196. if(loader.isInterrupted()){
  197. return;
  198. }
  199. Activity activity = RecordOverviewFragment.this.getActivity();
  200. if (activity != null){
  201. activity.runOnUiThread(new Runnable() {
  202. @Override
  203. public void run() {
  204. RecordOverviewFragment.this.expListView.setAdapter(currentAdapter);
  205. // Update view and remove loading spinner etc...
  206. RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
  207. if (adapter != null){
  208. adapter.notifyDataSetChanged();
  209. if (adapter.getGroupCount() >= 1){
  210. RecordOverviewFragment.this.expListView.expandGroup(DEFAULT_GROUPING_KEY_INDEX);
  211. } else {
  212. RecordOverviewFragment.this.setSectionToOpen(RecordOverviewFragment.this.sectionToOpen);
  213. }
  214. }
  215. if (RecordOverviewFragment.this.openSections != null && RecordOverviewFragment.this.openSections.size() != 0){
  216. for (int i = 0; i < RecordOverviewFragment.this.openSections.size(); i++){
  217. int index = RecordOverviewFragment.this.openSections.get(i);
  218. RecordOverviewFragment.this.expListView.expandGroup(index);
  219. }
  220. } else {
  221. RecordOverviewFragment.this.openSections = new ArrayList<Integer>();
  222. }
  223. if (mListPosition != -1 && mItemPosition != -1)
  224. RecordOverviewFragment.this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
  225. mListPosition = -1;
  226. mItemPosition = -1;
  227. registerListClickCallback(RecordOverviewFragment.this.expListView);
  228. RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
  229. RecordOverviewFragment.this.actualiseFilterButton();
  230. RecordOverviewFragment.this.showEmptyDataNotification();
  231. }
  232. });
  233. }
  234. }
  235. private RecordListAdapter doInBackground()
  236. {
  237. return populateListViewFromDB(RecordOverviewFragment.this.expListView);
  238. }
  239. @Override
  240. public void run()
  241. {
  242. //RecordOverviewFragment.this.addRecordToDB(40, 10, 4);
  243. updateUI(doInBackground());
  244. }
  245. });
  246. loader.start();
  247. this.actualiseFilterButton();
  248. }
  249. /**
  250. * Returns the Fragment layout ID
  251. * @return int The fragment layout ID
  252. * */
  253. public int getLayoutId(){
  254. return R.layout.fragment_record_list;
  255. }
  256. /**
  257. * Gets called if the user clicks on item in the filter menu.
  258. *
  259. * @param item {@link AbstractPopupItem AbstractPopupItem }
  260. * */
  261. public void onFilterMenuItemSelected(AbstractPopupItem item) {
  262. String title = item.getTitle();
  263. if (item instanceof SplitPopupItem){
  264. SplitPopupItem splitItem = (SplitPopupItem)item;
  265. if (splitItem.wasRightTouch){
  266. this.openTimestampToFilterDialog();
  267. } else {
  268. this.openTimestampFromFilterDialog();
  269. }
  270. return;
  271. }
  272. if (title != null){
  273. if(title.equals(FILTER_MENU_TITLE_BSSID)){
  274. this.openBSSIDFilterDialog();
  275. }
  276. if(title.equals(FILTER_MENU_TITLE_ESSID)){
  277. this.openESSIDFilterDialog();
  278. }
  279. if(title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  280. this.openProtocolsFilterDialog();
  281. }
  282. if(title.equals(FILTER_MENU_TITLE_SORTING)){
  283. this.openSortingDialog();
  284. }
  285. if(title.equals(FILTER_MENU_TITLE_REMOVE)){
  286. this.clearFilter();
  287. this.actualiseListViewInBackground();
  288. }
  289. if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
  290. this.openTimestampToFilterDialog();
  291. }
  292. if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  293. this.openTimestampFromFilterDialog();
  294. }
  295. }
  296. //return super.onOptionsItemSelected(item);
  297. }
  298. @Override
  299. public void onStart() {
  300. super.onStart();
  301. if (this.expListView.getExpandableListAdapter() != null){
  302. if (this.expListView.getExpandableListAdapter().getGroupCount() == 1){
  303. this.expListView.expandGroup(0);
  304. } else {
  305. this.setSectionToOpen(this.sectionToOpen);
  306. }
  307. }
  308. }
  309. @Override
  310. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  311. // Inflate the menu items for use in the action bar
  312. inflater.inflate(R.menu.records_overview_actions, menu);
  313. }
  314. @Override
  315. public boolean onOptionsItemSelected(MenuItem item) {
  316. switch (item.getItemId()) {
  317. case R.id.records_action_synchronize:
  318. AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
  319. builder.setTitle(MainActivity.getInstance().getString(R.string.rec_sync_rec));
  320. builder.setItems(new String[]{
  321. MainActivity.getInstance().getString(R.string.rec_via_bt),
  322. "With TraCINg",
  323. "Via WifiDirect"
  324. }, new DialogInterface.OnClickListener() {
  325. @Override
  326. public void onClick(DialogInterface dialog, int position) {
  327. switch(position){
  328. case 0:
  329. startActivityForResult(new Intent(getBaseContext(), BluetoothSyncActivity.class), 0);
  330. break;
  331. /*case 1:
  332. getActivity().startActivity(new Intent(getActivity(), NFCSyncActivity.class));
  333. break;*/
  334. case 1:
  335. startActivityForResult(new Intent(getActivity(), TracingSyncActivity.class), 0);
  336. break;
  337. case 2:
  338. startActivityForResult(new Intent(getActivity(), WiFiP2pSyncActivity.class), 0);
  339. break;
  340. }
  341. }
  342. });
  343. builder.create();
  344. builder.show();
  345. return true;
  346. case R.id.records_action_export:
  347. AlertDialog.Builder builderExport = new AlertDialog.Builder(getActivity());
  348. builderExport.setTitle(MainActivity.getInstance().getString(R.string.rec_choose_export_format));
  349. builderExport.setItems(R.array.format, new DialogInterface.OnClickListener() {
  350. @Override
  351. public void onClick(DialogInterface dialog, int position) {
  352. //RecordOverviewFragment.this.exportDatabase(position);
  353. Intent intent = new Intent(getActivity(), LogExport.class);
  354. intent.setAction(LogExport.ACTION_EXPORT_DATABASE);
  355. intent.putExtra(LogExport.FORMAT_EXPORT_DATABASE, position);
  356. RecordOverviewFragment.this.getActivity().startService(intent);
  357. }
  358. });
  359. builderExport.create();
  360. builderExport.show();
  361. return true;
  362. }
  363. return false;
  364. }
  365. public void openDeleteFilteredAttacksDialog() {
  366. // Use the Builder class for convenient dialog construction
  367. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  368. String deleteAttacksTitle = MainActivity.getInstance().getString(R.string.deleteAttacksTitle);
  369. String cancelTitle = MainActivity.getInstance().getString(R.string.cancel);
  370. String deleteTitle = MainActivity.getInstance().getString(R.string.delete);
  371. builder.setMessage(deleteAttacksTitle)
  372. .setPositiveButton(deleteTitle, new DialogInterface.OnClickListener() {
  373. private RecordOverviewFragment recordOverviewFragment = null;
  374. public void onClick(DialogInterface dialog, int id) {
  375. recordOverviewFragment.deleteFilteredAttacks();
  376. }
  377. public DialogInterface.OnClickListener init(RecordOverviewFragment rf){
  378. this.recordOverviewFragment = rf;
  379. return this;
  380. }
  381. }.init(this))
  382. .setNegativeButton(cancelTitle, new DialogInterface.OnClickListener() {
  383. public void onClick(DialogInterface dialog, int id) {
  384. // User cancelled the dialog
  385. }
  386. });
  387. AlertDialog dialog = builder.create();
  388. dialog.show();
  389. }
  390. @Override
  391. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  392. super.onActivityResult(requestCode, resultCode, data);
  393. if(requestCode == 0){
  394. if(resultCode == SyncUtils.SYNC_SUCCESSFUL){
  395. actualiseListViewInBackground();
  396. }
  397. }
  398. }
  399. /*****************************
  400. *
  401. * Public API
  402. *
  403. * ***************************/
  404. /**
  405. * Group records by SSID and expand given SSID
  406. *
  407. * @param SSID the SSID
  408. */
  409. public void showDetailsForSSID(Context context, String SSID) {
  410. Log.e("RecordOverviewFragment", "Implement showDetailsForSSID!!");
  411. this.clearFilter();
  412. int ESSID_INDEX = 2;
  413. ArrayList<String> ssids = new ArrayList<String>();
  414. this.sectionToOpen = SSID;
  415. this.groupingKey = this.groupingTitles().get(ESSID_INDEX);
  416. }
  417. /*****************************
  418. *
  419. * ListView Stuff
  420. *
  421. * ***************************/
  422. /**
  423. * Reloads the data in the ExpandableListView for the given filter object.
  424. * @param mylist {@link ExpandableListView ExpandableListView}
  425. * */
  426. private RecordListAdapter populateListViewFromDB(ExpandableListView mylist) {
  427. ArrayList<String> groupTitle = new ArrayList<String>();
  428. HashMap<String, ArrayList<ExpandableListItem>> sectionData = this.fetchDataForFilter(this.filter, groupTitle);
  429. RecordListAdapter adapter = null;
  430. if (mylist.getAdapter() != null && mylist.getAdapter() instanceof RecordListAdapter){
  431. adapter = (RecordListAdapter) mylist.getAdapter();
  432. adapter.setData(sectionData);
  433. adapter.setSectionHeader(groupTitle);
  434. } else {
  435. adapter = new RecordListAdapter( RecordOverviewFragment.this.getApplicationContext(), groupTitle, sectionData);
  436. }
  437. return adapter;
  438. }
  439. private HashMap<String, ArrayList<ExpandableListItem>> fetchDataForFilter(LogFilter filter, ArrayList<String> groupTitle){
  440. HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
  441. ArrayList<Record> data = dbh.getRecordsForFilter(filter == null ? this.filter : filter);
  442. // Adding Items to ListView
  443. String keys[] = new String[] { RecordOverviewFragment.this.getString(R.string.RecordBSSID), RecordOverviewFragment.this.getString(R.string.RecordSSID), RecordOverviewFragment.this.getString(R.string.RecordProtocol), RecordOverviewFragment.this.getString(R.string.RecordTimestamp)};
  444. int ids[] = new int[] {R.id.RecordTextFieldBSSID, R.id.RecordTextFieldSSID, R.id.RecordTextFieldProtocol, R.id.RecordTextFieldTimestamp };
  445. HashMap<String, Integer> mapping = new HashMap<String, Integer>();
  446. int i = 0;
  447. for(String key : keys){
  448. mapping.put(key, ids[i]);
  449. i++;
  450. }
  451. if (groupTitle == null){
  452. groupTitle = new ArrayList<String>();
  453. } else {
  454. groupTitle.clear();
  455. }
  456. for (Record val : data) {
  457. // DO GROUPING IN HERE
  458. HashMap<String, String> map = new HashMap<String, String>();
  459. map.put(RecordOverviewFragment.this.getString(R.string.RecordBSSID), val.getBssid());
  460. map.put(RecordOverviewFragment.this.getString(R.string.RecordSSID), val.getSsid());
  461. map.put(RecordOverviewFragment.this.getString(R.string.RecordProtocol), val.getProtocol());
  462. map.put(RecordOverviewFragment.this.getString(R.string.RecordTimestamp),
  463. RecordOverviewFragment.this.getDateAsString(val.getTimestamp()));
  464. ExpandableListItem item = new ExpandableListItem();
  465. item.setData(map);
  466. item.setId_Mapping(mapping);
  467. item.setTag(val.getAttack_id());
  468. String groupID = RecordOverviewFragment.this.getGroupValue(val);
  469. ArrayList<ExpandableListItem> items = sectionData.get(groupID);
  470. if (items == null) {
  471. items = new ArrayList<ExpandableListItem>();
  472. sectionData.put(groupID, items);
  473. groupTitle.add(groupID);
  474. }
  475. items.add(item);
  476. }
  477. if (this.groupingKey.equals(this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX))){
  478. Collections.sort(groupTitle,new DateStringComparator());
  479. } else {
  480. Collections.sort(groupTitle, new Comparator<String>() {
  481. @Override
  482. public int compare(String s1, String s2) {
  483. return s1.compareToIgnoreCase(s2);
  484. }
  485. });
  486. }
  487. return sectionData;
  488. }
  489. /**
  490. * The DateStringComparator compares formatted date strings by converting the into date.
  491. * This class is mainly used for grouping the records by their timestamp.
  492. */
  493. class DateStringComparator implements Comparator<String>
  494. {
  495. public int compare(String lhs, String rhs)
  496. {
  497. Date date1 = RecordOverviewFragment.this.convertStringToDate(lhs);
  498. Date date2 = RecordOverviewFragment.this.convertStringToDate(rhs);
  499. return date2.compareTo(date1);
  500. }
  501. }
  502. /**
  503. * register a broadcast receiver if not already registered
  504. * and also update the number of attacks per protocol
  505. */
  506. private void registerBroadcastReceiver() {
  507. if (!mReceiverRegistered) {
  508. mReceiver = new BroadcastReceiver() {
  509. @Override
  510. public void onReceive(Context context, Intent intent) {
  511. RecordOverviewFragment.this.actualiseListViewInBackground();
  512. }
  513. };
  514. LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
  515. this.mReceiverRegistered = true;
  516. }
  517. }
  518. /**
  519. * Actualises the list in a background thread
  520. */
  521. private void actualiseListViewInBackground(){
  522. if (loader != null && loader.isAlive()) loader.interrupt();
  523. loader = null;
  524. this.spinner.setVisibility(View.VISIBLE);
  525. this.actualiseFilterButton();
  526. loader = new Thread(new Runnable() {
  527. @Override
  528. public void run() {
  529. this.runOnUiThread(this.doInBackground());
  530. }
  531. private RecordListAdapter doInBackground(){
  532. return RecordOverviewFragment.this.populateListViewFromDB(RecordOverviewFragment.this.expListView);
  533. }
  534. private void runOnUiThread(final RecordListAdapter adapter){
  535. Activity actv = RecordOverviewFragment.this.getActivity();
  536. if (actv != null){
  537. actv.runOnUiThread(new Runnable() {
  538. @Override
  539. public void run() {
  540. this.actualiseUI();
  541. }
  542. private void actualiseUI(){
  543. if (adapter != null){
  544. RecordOverviewFragment.this.expListView.setAdapter(adapter);
  545. adapter.notifyDataSetChanged();
  546. RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
  547. }
  548. RecordOverviewFragment.this.showEmptyDataNotification();
  549. }
  550. });
  551. }
  552. }
  553. });
  554. loader.start();
  555. }
  556. /**
  557. * Shows a small toast if the data to show is empty (no records).
  558. */
  559. private void showEmptyDataNotification(){
  560. if (RecordOverviewFragment.this.noDataNotificationToast == null){
  561. RecordOverviewFragment.this.noDataNotificationToast = Toast.makeText(getApplicationContext(), R.string.no_data_notification, Toast.LENGTH_SHORT);
  562. }
  563. RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
  564. if (this.getFilterButton().getVisibility() == View.VISIBLE && this.filter.isSet()){
  565. this.noDataNotificationToast.setText(R.string.no_data_notification);
  566. } else {
  567. this.noDataNotificationToast.setText(R.string.no_data_notification_no_filter);
  568. }
  569. if (adapter == null || adapter.getData().isEmpty())
  570. RecordOverviewFragment.this.noDataNotificationToast.show();
  571. }
  572. /**This will open a section in the ExpandableListView with the same title as the parameter s.
  573. *
  574. * @param s String (the section title to open)
  575. *
  576. * */
  577. private void setSectionToOpen(String s){
  578. this.sectionToOpen = s;
  579. if (this.sectionToOpen != null && this.sectionToOpen.length() != 0){
  580. if (this.getGroupTitles().contains(this.sectionToOpen)){
  581. int section = this.getGroupTitles().indexOf(this.sectionToOpen);
  582. this.expListView.expandGroup(section);
  583. this.sectionToOpen = "";
  584. }
  585. }
  586. }
  587. /**
  588. * Returns the base context.
  589. * @return Context baseContext
  590. * */
  591. private Context getBaseContext(){
  592. return this.getActivity().getBaseContext();
  593. }
  594. /**Returns the application context.
  595. * @return Context application context
  596. * */
  597. private Context getApplicationContext(){
  598. return this.getActivity().getApplicationContext();
  599. }
  600. /**Sets the list view listener on the given ExpandableListView.
  601. *
  602. * @param mylist {@link ExpandableListView ExpandableListView }
  603. * */
  604. private void registerListClickCallback(ExpandableListView mylist) {
  605. mylist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
  606. @Override
  607. public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i2, long l) {
  608. RecordListAdapter adapter = (RecordListAdapter)expandableListView.getExpandableListAdapter();
  609. ExpandableListItem item = (ExpandableListItem)adapter.getChild(i,i2);
  610. mListPosition = i;
  611. mItemPosition = i2;
  612. HostageDBOpenHelper dbh = new HostageDBOpenHelper(getBaseContext());
  613. Record rec = dbh.getRecordOfAttackId((int) item.getTag());
  614. RecordOverviewFragment.this.pushRecordDetailViewForRecord(rec);
  615. return true;
  616. }
  617. });
  618. mylist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
  619. @Override
  620. public void onGroupExpand(int i) {
  621. RecordOverviewFragment.this.openSections.add(new Integer(i));
  622. }
  623. });
  624. mylist.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
  625. @Override
  626. public void onGroupCollapse(int i) {
  627. RecordOverviewFragment.this.openSections.remove(new Integer(i));
  628. }
  629. });
  630. }
  631. /*****************************
  632. *
  633. * Date Transformation / Conversion
  634. *
  635. * ***************************/
  636. /**Returns the localised date format for the given timestamp
  637. * @param timeStamp long */
  638. @SuppressLint("SimpleDateFormat")
  639. private String getDateAsString(long timeStamp) {
  640. Date date = (new Date(timeStamp));
  641. try {
  642. DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
  643. return formatter.format(date);
  644. } catch (Exception ex) {
  645. return "---";
  646. }
  647. }
  648. /**
  649. * Returns the timestamp in a own format.
  650. * Depending on the returned format the grouping by timestamp will change.
  651. *
  652. * e.g.
  653. * If you return a DateAsMonth formatted Date the records will be mapped by their month and year.
  654. * If you return the a DateAsDay formatted Date the records will be mapped by their day, month and year.
  655. * and so on...
  656. *
  657. * @param timestamp long
  658. * @return formatted date String
  659. */
  660. public String getFormattedDateForGrouping(long timestamp) {
  661. // DECIDE WHICH KIND OF FORMAT SHOULD BE USED
  662. // MONTH FORMAT
  663. String date = this.getDateAsMonthString(timestamp);
  664. // DAY FORMAT
  665. //String date = this.getDateAsDayString(timestamp);
  666. return date;
  667. }
  668. /**Returns a date as a formated string
  669. * @param timestamp date
  670. * @return String date format is localised*/
  671. @SuppressLint("SimpleDateFormat")
  672. private String getDateAsDayString(long timestamp) {
  673. try {
  674. Date netDate = (new Date(timestamp));
  675. String dateString;
  676. long date = this.dayMilliseconds(timestamp);
  677. if(this.todayMilliseconds() == date ){
  678. dateString = TODAY;
  679. }else if(this.yesterdayMilliseconds() == date ){
  680. dateString = YESTERDAY;
  681. } else {
  682. dateString = localisedDateFormatter.format(netDate);
  683. }
  684. return dateString;
  685. } catch (Exception ex) {
  686. return "---";
  687. }
  688. }
  689. /**
  690. * Converts a formatted DateString into a date.
  691. * @param dateString String
  692. * @return Date
  693. */
  694. private Date convertStringToDate(String dateString){
  695. if (dateString != null && dateString.length() != 0){
  696. SimpleDateFormat dateFormat = groupingDateFormatter; //new SimpleDateFormat(localDatePattern);
  697. Date date;
  698. try {
  699. if (dateString.equals(TODAY)){
  700. long millisec = RecordOverviewFragment.this.todayMilliseconds();
  701. date = new Date(millisec);
  702. } else if (dateString.equals(YESTERDAY)){
  703. long millisec = RecordOverviewFragment.this.yesterdayMilliseconds();
  704. date = new Date(millisec);
  705. } else {
  706. date = dateFormat.parse(dateString);
  707. }
  708. return date;
  709. } catch (java.text.ParseException e ) {
  710. date = new Date(0);
  711. return date;
  712. }
  713. } else {
  714. return new Date(0);
  715. }
  716. }
  717. /**
  718. * Returns the milliseconds for the day today (not the time).
  719. * @return long
  720. */
  721. private long todayMilliseconds(){
  722. Date current = new Date();
  723. calendar.setTimeInMillis(current.getTime());
  724. int day = calendar.get(Calendar.DATE);
  725. int month = calendar.get(Calendar.MONTH);
  726. int year = calendar.get(Calendar.YEAR);
  727. calendar.set(year, month, day, 0,0,0);
  728. long milli = calendar.getTimeInMillis();
  729. Date today = new Date(milli);
  730. return (milli / (long) 1000) * (long) 1000;
  731. }
  732. /**
  733. * Returns the milliseconds for the day yesterday (not the time).
  734. * @return long
  735. */
  736. private long yesterdayMilliseconds(){
  737. Date current = new Date();
  738. calendar.setTimeInMillis(current.getTime());
  739. int day = calendar.get(Calendar.DATE);
  740. int month = calendar.get(Calendar.MONTH);
  741. int year = calendar.get(Calendar.YEAR);
  742. calendar.set(year, month, day, 0,0,0);
  743. calendar.add(Calendar.DATE, -1);
  744. long milli = calendar.getTimeInMillis();
  745. Date today = new Date(milli);
  746. return (milli / (long) 1000) * (long) 1000;
  747. }
  748. /**
  749. * returns just the date not the time of a date.
  750. * @param date Date
  751. * @return long
  752. */
  753. private long dayMilliseconds(long date){
  754. //Date current = new Date();
  755. calendar.setTimeInMillis(date);
  756. int day = calendar.get(Calendar.DATE);
  757. int month = calendar.get(Calendar.MONTH);
  758. int year = calendar.get(Calendar.YEAR);
  759. calendar.set(year, month, day, 0,0,0);
  760. long milli = calendar.getTimeInMillis();
  761. Date test = new Date(milli);
  762. return (milli / (long) 1000) * (long) 1000;
  763. }
  764. /**Returns a date as a formated string
  765. * @param timeStamp date
  766. * @return String date format is localised*/
  767. @SuppressLint("SimpleDateFormat")
  768. private String getDateAsMonthString(long timeStamp) {
  769. try {
  770. Date netDate = (new Date(timeStamp));
  771. return groupingDateFormatter.format(netDate);
  772. } catch (Exception ex) {
  773. return "xx";
  774. }
  775. }
  776. /*****************************
  777. *
  778. * Getter / Setter
  779. *
  780. * ***************************/
  781. public boolean isShowFilterButton() {
  782. return showFilterButton;
  783. }
  784. public void setShowFilterButton(boolean showFilterButton) {
  785. this.showFilterButton = showFilterButton;
  786. }
  787. /**
  788. * Set the group key for grouping the records.
  789. * All possible grouping keys are:
  790. * R.string.date,
  791. * R.string.rec_protocol,
  792. * R.string.ESSID,
  793. * R.string.BSSID
  794. * @param key String
  795. */
  796. public void setGroupKey(String key){
  797. this.groupingKey = key;
  798. }
  799. public void setFilter(LogFilter filter){
  800. this.filter = filter;
  801. }
  802. /*****************************
  803. *
  804. * Open Dialog Methods
  805. *
  806. * ***************************/
  807. /**Opens the grouping dialog*/
  808. private void openGroupingDialog(){
  809. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_GROUP, this.groupingTitles(), this.selectedGroup(), false , this);
  810. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_GROUP);
  811. }
  812. /**opens the bssid filter dialog*/
  813. private void openBSSIDFilterDialog(){
  814. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID,this.bssids(), this.selectedBSSIDs(), true , this);
  815. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
  816. }
  817. /**opens the essid filter dialog*/
  818. private void openESSIDFilterDialog(){
  819. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID,this.essids(), this.selectedESSIDs(), true , this);
  820. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
  821. }
  822. /**opens the protocol filter dialog*/
  823. private void openProtocolsFilterDialog(){
  824. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS,this.protocolTitles(), this.selectedProtocols(), true , this);
  825. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
  826. }
  827. /**opens the timestamp filter dialog (minimal timestamp required)*/
  828. private void openTimestampFromFilterDialog(){
  829. this.wasBelowTimePicker = false;
  830. DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
  831. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  832. if (this.filter.aboveTimestamp != Long.MIN_VALUE)newFragment.setDate(this.filter.aboveTimestamp);
  833. }
  834. /**opens time timestamp filter dialog (maximal timestamp required)*/
  835. private void openTimestampToFilterDialog(){
  836. this.wasBelowTimePicker = true;
  837. DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
  838. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  839. if (this.filter.belowTimestamp != Long.MAX_VALUE) newFragment.setDate(this.filter.belowTimestamp);
  840. }
  841. /**opens the sorting dialog*/
  842. private void openSortingDialog(){
  843. ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_SORTING,this.sortTypeTiles(), this.selectedSorttype(), false , this);
  844. newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
  845. }
  846. /*****************************
  847. *
  848. * Grouping Stuff
  849. *
  850. * ***************************/
  851. /**returns the group title for the given record. Uses the groupingKey to decied which value of the record should be used.
  852. * @param rec {@link Record Record }
  853. * @return String grouptitle*/
  854. public String getGroupValue(Record rec){
  855. int index = this.groupingTitles().indexOf(this.groupingKey);
  856. switch (index){
  857. case 1:
  858. return rec.getProtocol();
  859. case 2:
  860. return rec.getSsid();
  861. case 3:
  862. return rec.getBssid();
  863. case 0:
  864. return this.getFormattedDateForGrouping(rec.getTimestamp());
  865. default:
  866. return this.getFormattedDateForGrouping(rec.getTimestamp());
  867. }
  868. }
  869. /**Returns the Group titles for the specified grouping key. e.g. groupingKey is "ESSID" it returns all available essids.
  870. * @return ArrayList<String> grouptitles*/
  871. public List<String> getGroupTitles(){
  872. int index = this.groupingTitles().indexOf(this.groupingKey);
  873. switch (index){
  874. case 1:
  875. return this.protocolTitles();
  876. case 2:
  877. return this.essids();
  878. case 3:
  879. return this.bssids();
  880. case 0:
  881. default:
  882. RecordListAdapter adapter = (RecordListAdapter) this.expListView.getExpandableListAdapter();
  883. if (adapter != null){
  884. return adapter.getSectionHeaders();
  885. }
  886. return new ArrayList<String>();
  887. }
  888. }
  889. /*****************************
  890. *
  891. * Filter Stuff
  892. *
  893. * ***************************/
  894. /**Returns the FilterButton.
  895. * @return ImageButton filterButton*/
  896. private ImageButton getFilterButton(){
  897. return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
  898. }
  899. /**Opens the filter menu on a anchor view. The filter menu will always be on top of the anchor.
  900. * @param v View the anchorView*/
  901. private void openFilterPopupMenuOnView(View v){
  902. SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
  903. public void onItemClick(Object ob) {
  904. if (ob instanceof AbstractPopupItem){
  905. AbstractPopupItem item = (AbstractPopupItem) ob;
  906. RecordOverviewFragment.this.onFilterMenuItemSelected(item);
  907. }
  908. }
  909. });
  910. filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
  911. for(String title : RecordOverviewFragment.this.filterMenuTitles()){
  912. AbstractPopupItem item = null;
  913. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) continue;
  914. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  915. item = new SplitPopupItem(this.getActivity());
  916. item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
  917. item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
  918. if (this.filter.hasBelowTimestamp()){
  919. item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
  920. }
  921. if (this.filter.hasAboveTimestamp()){
  922. item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
  923. }
  924. } else {
  925. item = new SimplePopupItem(this.getActivity());
  926. item.setTitle(title);
  927. ((SimplePopupItem)item).setSelected(this.isFilterSetForTitle(title));
  928. }
  929. filterMenu.addItem(item);
  930. }
  931. filterMenu.showOnView(v);
  932. }
  933. /**Returns true if the filter object is set for the given title otherwise false. e.g. the filter object has protocols,
  934. * so the method will return for the title FILTER_MENU_TITLE_PROTOCOLS TRUE.
  935. * @param title String
  936. * @return boolean value
  937. * */
  938. private boolean isFilterSetForTitle(String title){
  939. if (title.equals(FILTER_MENU_TITLE_BSSID)){
  940. return this.filter.hasBSSIDs();
  941. }
  942. if (title.equals(FILTER_MENU_TITLE_ESSID)){
  943. return this.filter.hasESSIDs();
  944. }
  945. if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  946. return this.filter.hasProtocols();
  947. }
  948. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
  949. return this.filter.hasBelowTimestamp();
  950. }
  951. if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
  952. return this.filter.hasAboveTimestamp();
  953. }
  954. return false;
  955. }
  956. /**clears the filter. Does not invoke populatelistview!*/
  957. private void clearFilter(){
  958. if(filter == null) this.filter = new LogFilter();
  959. this.filter.clear();
  960. }
  961. /**Returns all grouping titles.
  962. * @return ArrayList<String> tiles*/
  963. public ArrayList<String> groupingTitles(){
  964. ArrayList<String> titles = new ArrayList<String>();
  965. titles.add(MainActivity.getContext().getString(R.string.date));
  966. titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
  967. titles.add(MainActivity.getContext().getString(R.string.ESSID));
  968. titles.add(MainActivity.getContext().getString(R.string.BSSID));
  969. return titles;
  970. }
  971. /**
  972. * Returns a bool array. This array is true at the index of the groupingKey in groupingTitles(), otherwise false.
  973. * @return boolean[] selection
  974. * */
  975. public boolean[] selectedGroup(){
  976. ArrayList<String> groups = this.groupingTitles();
  977. boolean[] selected = new boolean[groups.size()];
  978. int i = 0;
  979. for(String group : groups){
  980. selected[i] =(group.equals(this.groupingKey));
  981. i++;
  982. }
  983. return selected;
  984. }
  985. /**Returns all protocol titles / names.
  986. * @return ArrayList<String> protocolTitles
  987. * */
  988. public ArrayList<String> protocolTitles(){
  989. ArrayList<String> titles = new ArrayList<String>();
  990. for (String protocol : this.getResources().getStringArray(
  991. R.array.protocols)) {
  992. titles.add(protocol);
  993. }
  994. titles.add("PORTSCAN");
  995. return titles;
  996. }
  997. /**Return a boolean array of the selected / filtered protocols. If the filter object has
  998. * an protocol from the protocolTitles() array, the index of it will be true, otherwise false.
  999. * @return boolean[] protocol selection
  1000. * */
  1001. public boolean[] selectedProtocols(){
  1002. ArrayList<String> protocols = this.protocolTitles();
  1003. boolean[] selected = new boolean[protocols.size()];
  1004. int i = 0;
  1005. for(String protocol : protocols){
  1006. selected[i] =(this.filter.protocols.contains(protocol));
  1007. i++;
  1008. }
  1009. return selected;
  1010. }
  1011. /**
  1012. * Returns the Sorttype Titles
  1013. * @return ArayList<String> Sort type titles
  1014. * */
  1015. public ArrayList<String> sortTypeTiles(){
  1016. ArrayList<String> titles = new ArrayList<String>();
  1017. titles.add(MainActivity.getContext().getString(R.string.rec_time));
  1018. titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
  1019. titles.add(MainActivity.getContext().getString(R.string.ESSID));
  1020. titles.add(MainActivity.getContext().getString(R.string.BSSID));
  1021. return titles;
  1022. }
  1023. /**
  1024. * Returns an boolean array. The array is true at the index of the selected sort type..
  1025. * The index of the selected sort type is the same index in the sortTypeTiles array.
  1026. * @return boolean array, length == sortTypeTiles().length
  1027. * */
  1028. public boolean[] selectedSorttype(){
  1029. ArrayList<String> types = this.sortTypeTiles();
  1030. boolean[] selected = new boolean[types.size()];
  1031. int i = 0;
  1032. for(String sorttype : types){
  1033. selected[i] =(this.filter.sorttype.toString().equals(sorttype));
  1034. i++;
  1035. }
  1036. return selected;
  1037. }
  1038. /**
  1039. * Returns all unique bssids.
  1040. * @return ArrayList<String>
  1041. * */
  1042. public ArrayList<String> bssids(){
  1043. ArrayList<String> records = dbh.getUniqueBSSIDRecords();
  1044. return records;
  1045. }
  1046. /**
  1047. * Returns an boolean array. The array is true at the indices of the selected bssids.
  1048. * The index of the selected bssid is the same index in the bssids() array.
  1049. * @return boolean array, length == bssids().length
  1050. * */
  1051. public boolean[] selectedBSSIDs(){
  1052. ArrayList<String> bssids = this.bssids();
  1053. boolean[] selected = new boolean[bssids.size()];
  1054. int i = 0;
  1055. for(String bssid : bssids){
  1056. selected[i] =(this.filter.BSSIDs.contains(bssid));
  1057. i++;
  1058. }
  1059. return selected;
  1060. }
  1061. /**
  1062. * Returns all unique essids.
  1063. * @return ArrayList<String>
  1064. * */
  1065. public ArrayList<String> essids(){
  1066. ArrayList<String> records = dbh.getUniqueESSIDRecords();
  1067. return records;
  1068. }
  1069. /**
  1070. * Returns an boolean array. The array is true at the indices of the selected essids.
  1071. * The index of the selected essid is the same index in the essids() array.
  1072. * @return boolean array, length == essids().length
  1073. * */
  1074. public boolean[] selectedESSIDs(){
  1075. ArrayList<String> essids = this.essids();
  1076. boolean[] selected = new boolean[essids.size()];
  1077. int i = 0;
  1078. for(String essid : essids){
  1079. selected[i] =(this.filter.ESSIDs.contains(essid));
  1080. i++;
  1081. }
  1082. return selected;
  1083. }
  1084. /**
  1085. * Returns all filter menu titles.
  1086. * @return ArrayList<String>
  1087. * */
  1088. private ArrayList<String> filterMenuTitles(){
  1089. ArrayList<String> titles = new ArrayList<String>();
  1090. titles.add(FILTER_MENU_TITLE_BSSID);
  1091. titles.add(FILTER_MENU_TITLE_ESSID);
  1092. titles.add(FILTER_MENU_TITLE_PROTOCOLS);
  1093. titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
  1094. titles.add(FILTER_MENU_TITLE_TIMESTAMP_BELOW);
  1095. if (this.filter.isSet())titles.add(FILTER_MENU_TITLE_REMOVE);
  1096. return titles;
  1097. }
  1098. /*****************************
  1099. *
  1100. * Listener Actions
  1101. *
  1102. * ***************************/
  1103. /**
  1104. * Will be called if the users selects a timestamp.
  1105. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1106. * */
  1107. public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
  1108. if(this.wasBelowTimePicker){
  1109. this.filter.setBelowTimestamp(dialog.getDate());
  1110. } else {
  1111. this.filter.setAboveTimestamp(dialog.getDate());
  1112. }
  1113. this.actualiseListViewInBackground();
  1114. this.actualiseFilterButton();
  1115. }
  1116. /**
  1117. * Will be called if the users cancels a timestamp selection.
  1118. * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
  1119. * */
  1120. public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
  1121. if(this.wasBelowTimePicker){
  1122. this.filter.setBelowTimestamp(Long.MAX_VALUE);
  1123. } else {
  1124. this.filter.setAboveTimestamp(Long.MIN_VALUE);
  1125. }
  1126. this.actualiseListViewInBackground();
  1127. this.actualiseFilterButton();
  1128. }
  1129. /**
  1130. * Will be called if the users clicks the positiv button on a ChechlistDialog.
  1131. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1132. */
  1133. public void onDialogPositiveClick(ChecklistDialog dialog) {
  1134. String title = dialog.getTitle();
  1135. if(title.equals(FILTER_MENU_TITLE_BSSID)){
  1136. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1137. if (titles.size() == this.bssids().size()){
  1138. this.filter.setBSSIDs(new ArrayList<String>());
  1139. } else {
  1140. this.filter.setBSSIDs(titles);
  1141. }
  1142. }
  1143. if(title.equals(FILTER_MENU_TITLE_ESSID)){
  1144. ArrayList<String> titles =dialog.getSelectedItemTitles();
  1145. if (titles.size() == this.essids().size()){
  1146. this.filter.setESSIDs(new ArrayList<String>());
  1147. } else {
  1148. this.filter.setESSIDs(titles);
  1149. }
  1150. }
  1151. if(title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
  1152. ArrayList<String> protocols = dialog.getSelectedItemTitles();
  1153. if (protocols.size() == this.protocolTitles().size()){
  1154. this.filter.setProtocols(new ArrayList<String>());
  1155. } else {
  1156. this.filter.setProtocols(dialog.getSelectedItemTitles());
  1157. }
  1158. }
  1159. if(title.equals(FILTER_MENU_TITLE_SORTING)){
  1160. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1161. if (titles.size() == 0) return;
  1162. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1163. String t = titles.get(0);
  1164. int sortType = this.sortTypeTiles().indexOf(t);
  1165. this.filter.setSorttype(SortType.values()[sortType]);
  1166. }
  1167. if (title.equals(FILTER_MENU_TITLE_GROUP)){
  1168. ArrayList<String> titles = dialog.getSelectedItemTitles();
  1169. if (titles.size() == 0) return;
  1170. // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
  1171. this.groupingKey = titles.get(0);
  1172. }
  1173. this.actualiseListViewInBackground();
  1174. this.actualiseFilterButton();
  1175. }
  1176. /**Paints the filter button if the current filter object is set.*/
  1177. private void actualiseFilterButton(){
  1178. if (this.filter.isSet() ){
  1179. ImageButton filterButton = this.getFilterButton();
  1180. if (filterButton != null){
  1181. filterButton.setImageResource(R.drawable.ic_filter_pressed);
  1182. filterButton.invalidate();
  1183. }
  1184. } else {
  1185. ImageButton filterButton = this.getFilterButton();
  1186. if (filterButton != null){
  1187. filterButton.setImageResource(R.drawable.ic_filter);
  1188. filterButton.invalidate();
  1189. }
  1190. }
  1191. }
  1192. /**
  1193. * Deletes the current displayed attacks.
  1194. */
  1195. public void deleteFilteredAttacks(){
  1196. LogFilter filter = this.filter;
  1197. dbh.deleteAttacksByFilter(filter);
  1198. this.actualiseListViewInBackground();
  1199. }
  1200. /**
  1201. * Will be called if the users clicks the negativ button on a ChechlistDialog.
  1202. * @param dialog {@link ChecklistDialog ChecklistDialog }
  1203. */
  1204. public void onDialogNegativeClick(ChecklistDialog dialog) {}
  1205. /*****************************
  1206. *
  1207. * TEST
  1208. *
  1209. * ***************************/
  1210. /**
  1211. * This will clear the database at first and than add new attacks.
  1212. * @param createNetworks number of networks to create
  1213. * @param attacksPerNetwork maximal number of attack per network
  1214. * @param maxMessagePerAttack maximal number of messages per attack
  1215. * */
  1216. private void addRecordToDB( int createNetworks, int attacksPerNetwork, int maxMessagePerAttack) {
  1217. if ((dbh.getRecordCount() > 0)) dbh.clearData();
  1218. Calendar cal = Calendar.getInstance();
  1219. int maxProtocolsIndex = this.getResources().getStringArray(
  1220. R.array.protocols).length;
  1221. Random random = new Random();
  1222. LatLng tudarmstadtLoc = new LatLng(49.86923, 8.6632768);
  1223. final double ssidRadius = 0.1;
  1224. final double bssidRadius = 0.004;
  1225. int attackId = 0;
  1226. ArrayList<NetworkRecord> networkRecords = new ArrayList<NetworkRecord>();
  1227. ArrayList<AttackRecord> attackRecords = new ArrayList<AttackRecord>();
  1228. ArrayList<MessageRecord> messageRecords = new ArrayList<MessageRecord>();
  1229. for (int numOfNetworks = 0; numOfNetworks < createNetworks; numOfNetworks++){
  1230. String ssidName = "WiFi" + ((numOfNetworks) + 1);
  1231. String bssidName = "127.0.0." + ((numOfNetworks) + 1);
  1232. int protocolIndex = numOfNetworks % maxProtocolsIndex;
  1233. String protocolName = this.getResources().getStringArray(
  1234. R.array.protocols)[protocolIndex];
  1235. int numOfAttackPerNetwork = (Math.abs(random.nextInt()) % Math.max(1, attacksPerNetwork + 1));
  1236. NetworkRecord network = new NetworkRecord();
  1237. network.setBssid(bssidName);
  1238. network.setSsid(ssidName);
  1239. LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius + 2.0 * ssidRadius * Math.random());
  1240. double latitude = ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1241. double longitude = ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random();
  1242. long timestamp = cal.getTimeInMillis();
  1243. network.setTimestampLocation(timestamp);
  1244. network.setLongitude(longitude);
  1245. network.setLatitude(latitude);
  1246. network.setAccuracy(0.f);
  1247. //dbh.updateNetworkInformation(network);
  1248. networkRecords.add(network);
  1249. // ATTACKS PER NETWORK
  1250. for (int attackNumber = 0; attackNumber < numOfAttackPerNetwork; attackNumber++) {
  1251. int numRecordsPerAttack = (Math.abs(random.nextInt()) % (Math.max( maxMessagePerAttack, 1))) + 1;
  1252. if (maxMessagePerAttack <= 0) numRecordsPerAttack = 0;
  1253. /* ADD A ATTACK*/
  1254. AttackRecord attack = new AttackRecord(true);
  1255. attack.setBssid(bssidName);
  1256. attack.setProtocol(protocolName);
  1257. attack.setLocalIP(bssidName);
  1258. //dbh.addAttackRecord(attack);
  1259. attackRecords.add(attack);
  1260. // MESSAGE PER ATTACK
  1261. for (int messageID = attackId; messageID < attackId + numRecordsPerAttack; messageID++) {
  1262. MessageRecord message = new MessageRecord(true);
  1263. //message.setId(messageID);
  1264. message.setAttack_id(attack.getAttack_id());
  1265. // GO BACK IN TIME
  1266. message.setTimestamp(cal.getTimeInMillis()
  1267. - ((messageID * 60 * 60 * 24) * 1000) + (1000 * ((messageID - attackId) + 1)));
  1268. if ((messageID - attackId) % 2 == 0){
  1269. message.setType(MessageRecord.TYPE.RECEIVE);
  1270. } else {
  1271. message.setType(MessageRecord.TYPE.SEND);
  1272. }
  1273. message.setPacket("");
  1274. //dbh.addMessageRecord(message);
  1275. messageRecords.add(message);
  1276. }
  1277. attackId+=numRecordsPerAttack;
  1278. }
  1279. }
  1280. dbh.updateNetworkInformation(networkRecords);
  1281. dbh.insertAttackRecords(attackRecords);
  1282. dbh.insertMessageRecords(messageRecords);
  1283. // int countAllLogs = dbh.getAllRecords().size();
  1284. // int countRecords = dbh.getRecordCount();
  1285. // int countAttacks = dbh.getAttackCount();
  1286. //
  1287. // if ((countRecords == 0)) {
  1288. // Record rec = dbh.getRecordOfAttackId(0);
  1289. // Record rec2 = dbh.getRecord(0);
  1290. //
  1291. // System.out.println("" + "Could not create logs!");
  1292. // }
  1293. }
  1294. /**Navigation. Shows the record detail view for the given record
  1295. * @param record {@link Record Record } to show
  1296. * */
  1297. private void pushRecordDetailViewForRecord(Record record){
  1298. FragmentManager fm = this.getActivity().getFragmentManager();
  1299. if (fm != null){
  1300. RecordDetailFragment newFragment = new RecordDetailFragment();
  1301. newFragment.setRecord(record);
  1302. newFragment.setUpNavigatible(true);
  1303. MainActivity.getInstance().injectFragment(newFragment);
  1304. }
  1305. }
  1306. }