Skip to content

Commit

Permalink
align variable naming and adjust export formats
Browse files Browse the repository at this point in the history
  • Loading branch information
zafodB committed Jul 2, 2021
1 parent 655a9d3 commit ffd31c6
Show file tree
Hide file tree
Showing 4 changed files with 224 additions and 202 deletions.
212 changes: 106 additions & 106 deletions src/main/java/dk/aau/netsec/hostage/logging/LogExport.java
Expand Up @@ -26,15 +26,15 @@
* @author Lars Pandikow
*/
public class LogExport extends IntentService {
public static final String ACTION_EXPORT_DATABASE = "dk.aau.netsec.hostage.logging.ACTION_EXPORT_DATABASE";
public static final String FORMAT_EXPORT_DATABASE = "dk.aau.netsec.hostage.logging.FORMAT_EXPORT_DATABASE";
// public static final String ACTION_EXPORT_DATABASE = "dk.aau.netsec.hostage.logging.ACTION_EXPORT_DATABASE";
// public static final String FORMAT_EXPORT_DATABASE = "dk.aau.netsec.hostage.logging.FORMAT_EXPORT_DATABASE";

static Handler mMainThreadHandler = null;
// static Handler mMainThreadHandler = null;

static SharedPreferences pref;
static DaoSession dbSession;
static DAOHelper daoHelper;
public static Formatter formatter;
// static SharedPreferences pref;
// static DaoSession dbSession;
// static DAOHelper daoHelper;
// public static Formatter formatter;
public LogExport() {
super(LogExport.class.getName());

Expand All @@ -43,10 +43,10 @@ public LogExport() {
@Override
public void onCreate() {
super.onCreate();
pref = PreferenceManager.getDefaultSharedPreferences(this);
dbSession = HostageApplication.getInstances().getDaoSession();
daoHelper = new DAOHelper(dbSession,this);
mMainThreadHandler = new Handler();
// pref = PreferenceManager.getDefaultSharedPreferences(this);
// dbSession = HostageApplication.getInstances().getDaoSession();
// daoHelper = new DAOHelper(dbSession,this);
// mMainThreadHandler = new Handler();
}

/**
Expand All @@ -56,74 +56,74 @@ public void onCreate() {
*/
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();

if (ACTION_EXPORT_DATABASE.equals(action)) {
final int format = intent.getIntExtra(FORMAT_EXPORT_DATABASE, 0);
formatter = (format == 0 ? TraCINgFormatter.getInstance() : null);

Intent filipsIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

filipsIntent.setType("application/json");

filipsIntent.putExtra(Intent.EXTRA_TITLE, getFileName("file",".json"));

// startActivityForResult


// if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// if(format == 0) {
// exportDatabase(formatter);
// } else if(format == 1) {
// exportJSONFormat();
// }
// }
// else{
// Toast.makeText(this, "Could not write out to storage", Toast.LENGTH_SHORT).show();
// }
}
}
// if (intent != null) {
// final String action = intent.getAction();
//
// if (ACTION_EXPORT_DATABASE.equals(action)) {
// final int format = intent.getIntExtra(FORMAT_EXPORT_DATABASE, 0);
// formatter = (format == 0 ? TraCINgFormatter.getInstance() : null);
//
// Intent filipsIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
//
// filipsIntent.setType("application/json");
//
// filipsIntent.putExtra(Intent.EXTRA_TITLE, getFileName("file",".json"));
//
//// startActivityForResult
//
//
//// if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//// if(format == 0) {
//// exportDatabase(formatter);
//// } else if(format == 1) {
//// exportJSONFormat();
//// }
//// }
//// else{
//// Toast.makeText(this, "Could not write out to storage", Toast.LENGTH_SHORT).show();
//// }
// }
// }
}

private void exportJSONFormat(){
JSONHelper jsonHelper = new JSONHelper();
try {
File file = getDirFile("file", ".json");
String filename = getFileName("file",".json");
ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();
jsonHelper.jsonWriter(records,file);

makeToast(filename+" saved on external (if you have an sd card) or internal memory! ", Toast.LENGTH_LONG);
}catch (Exception e){
makeToast("Could not write to a JSON File in SD Card or Internal Storage",Toast.LENGTH_SHORT);
}

}

private static File getDirFile(String format,String extension){
String filename = getFileName(format,extension);
String externalLocation = pref.getString("pref_external_location", "");

String root = getExternalStoragePath();
File dir = new File(root + externalLocation);
dir.mkdirs();
File file = new File(dir, filename);
// JSONHelper jsonHelper = new JSONHelper();
// try {
// File file = getDirFile("file", ".json");
// String filename = getFileName("file",".json");
// ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();
// jsonHelper.jsonWriter(records,file);
//
// makeToast(filename+" saved on external (if you have an sd card) or internal memory! ", Toast.LENGTH_LONG);
// }catch (Exception e){
// makeToast("Could not write to a JSON File in SD Card or Internal Storage",Toast.LENGTH_SHORT);
// }

return file;
}

private static String getExternalStoragePath(){
String path = System.getenv("SECONDARY_STORAGE"); //SD card
if(path!=null && !path.trim().isEmpty()){
return path;
}
return System.getenv("EXTERNAL_STORAGE"); //internal Storage
}

public static String getFileName(String format,String extension){
return "hostage_" + (format) + "_"+ System.currentTimeMillis() + extension;
}
// private static File getDirFile(String format,String extension){
// String filename = getFileName(format,extension);
// String externalLocation = pref.getString("pref_external_location", "");
//
// String root = getExternalStoragePath();
// File dir = new File(root + externalLocation);
// dir.mkdirs();
// File file = new File(dir, filename);
//
// return file;
// }

// private static String getExternalStoragePath(){
// String path = System.getenv("SECONDARY_STORAGE"); //SD card
// if(path!=null && !path.trim().isEmpty()){
// return path;
// }
// return System.getenv("EXTERNAL_STORAGE"); //internal Storage
// }
//
// public static String getFileName(String format,String extension){
// return "hostage_" + (format) + "_"+ System.currentTimeMillis() + extension;
// }

/**
* Exports all records in a given format. Before exporting checks export
Expand All @@ -132,38 +132,38 @@ public static String getFileName(String format,String extension){
* @param format Integer coded export format
* @see RecordAll #toString(int)
*/
public static void exportDatabase(Formatter format) {
try {
FileOutputStream log;
String filename = getFileName(format.toString(),".log");
log = new FileOutputStream(getDirFile(format.toString(),".log"));

ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();
for (RecordAll record : records) {
log.write((record.toString(format)).getBytes());
}
log.flush();
log.close();
makeToast(filename + " saved on external (if you have an sd card) or internal memory! ", Toast.LENGTH_LONG);
} catch (Exception e) {
makeToast("Could not write to SD Card or Internal Storage", Toast.LENGTH_SHORT);
e.printStackTrace();
}
}
/**
* Checks if external storage is available for read and write.
*
* @return True if external storage is available for read and write, else
* false.
*/
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}

private static void makeToast(final String text, final int length){
mMainThreadHandler.post(() -> Toast.makeText(Hostage.getContext(), text, length).show());
}
// public static void exportDatabase(Formatter format) {
// try {
// FileOutputStream log;
// String filename = getFileName(format.toString(),".log");
// log = new FileOutputStream(getDirFile(format.toString(),".log"));
//
// ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();
// for (RecordAll record : records) {
// log.write((record.toString(format)).getBytes());
// }
// log.flush();
// log.close();
// makeToast(filename + " saved on external (if you have an sd card) or internal memory! ", Toast.LENGTH_LONG);
// } catch (Exception e) {
// makeToast("Could not write to SD Card or Internal Storage", Toast.LENGTH_SHORT);
// e.printStackTrace();
// }
// }
//
// /**
// * Checks if external storage is available for read and write.
// *
// * @return True if external storage is available for read and write, else
// * false.
// */
// private static boolean isExternalStorageWritable() {
// String state = Environment.getExternalStorageState();
// return Environment.MEDIA_MOUNTED.equals(state);
// }
//
// private static void makeToast(final String text, final int length){
// mMainThreadHandler.post(() -> Toast.makeText(Hostage.getContext(), text, length).show());
// }

}
84 changes: 56 additions & 28 deletions src/main/java/dk/aau/netsec/hostage/logging/LogSaveWorker.java
Expand Up @@ -2,7 +2,7 @@

import android.content.Context;
import android.net.Uri;
import android.widget.Toast;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
Expand All @@ -11,17 +11,23 @@
import org.json.JSONArray;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import dk.aau.netsec.hostage.HostageApplication;
import dk.aau.netsec.hostage.commons.JSONHelper;
import dk.aau.netsec.hostage.logging.formatter.Formatter;
import dk.aau.netsec.hostage.logging.formatter.TraCINgFormatter;
import dk.aau.netsec.hostage.persistence.DAO.DAOHelper;
import dk.aau.netsec.hostage.ui.fragment.RecordOverviewFragment;


/**
* @author Filip Adamik
* Created on 21/06/2021
Expand All @@ -41,53 +47,75 @@ public LogSaveWorker(@NonNull Context context, @NonNull WorkerParameters workerP
public Result doWork() {

dbSession = HostageApplication.getInstances().getDaoSession();
daoHelper = new DAOHelper(dbSession,filipsContext);
daoHelper = new DAOHelper(dbSession, filipsContext);

Uri uri = Uri.parse(getInputData().getString(RecordOverviewFragment.WORKER_DATA_URI_KEY));
int exportFormat = getInputData().getInt(RecordOverviewFragment.LOG_EXPORT_FORMAT, RecordOverviewFragment.EXPORT_FORMAT_POSITION_PLAINTEXT);

if (exportFormat == RecordOverviewFragment.EXPORT_FORMAT_POSITION_JSON) {

// String filipsDataToWrite = getInputData().getString("filipsKey");
Uri uri = Uri.parse(getInputData().getString("filipsHorribleUri"));
int exportFormat = getInputData().getInt(RecordOverviewFragment.LOG_EXPORT_FORMAT, RecordOverviewFragment.POSITION_EXPORT_FORMAT_PLAINTEXT);
writeJSONFile(uri);

return Result.success();
} else if (exportFormat == RecordOverviewFragment.EXPORT_FORMAT_POSITION_PLAINTEXT) {

writePlaintextFile(uri);

writeJSONFile(uri);
return Result.success();
return Result.success();
}

return Result.failure();
}

// private void exportJSONFormat(){
public static String getFileName(int exportFormat) {
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmm");
Date date = new Date(System.currentTimeMillis());

// try {
//
//
//
//
// makeToast(filename+" saved on external (if you have an sd card) or internal memory! ", Toast.LENGTH_LONG);
// }catch (Exception e){
// makeToast("Could not write to a JSON File in SD Card or Internal Storage",Toast.LENGTH_SHORT);
// }
if (exportFormat == RecordOverviewFragment.EXPORT_FORMAT_POSITION_JSON) {
return "hostage_" + formatter.format(date) + ".json";
} else {
return "hostage_" + formatter.format(date) + ".txt";
}
}

private void writeJSONFile(@NonNull Uri uri) {
JSONHelper jsonHelper = new JSONHelper();
private void writePlaintextFile(Uri outputFileUri) {
Formatter formatter = TraCINgFormatter.getInstance();
ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();


OutputStream outputStream;
try {
outputStream = filipsContext.getContentResolver().openOutputStream(uri);
outputStream = filipsContext.getContentResolver().openOutputStream(outputFileUri);

// jsonHelper.jsonWriter(records, outputStream);
for (RecordAll record : records) {
outputStream.write((record.toString(formatter)).getBytes());
}

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, "utf8"),8192);
//
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

private void writeJSONFile(@NonNull Uri outputFileUri) {
JSONHelper jsonHelper = new JSONHelper();
ArrayList<RecordAll> records = daoHelper.getAttackRecordDAO().getAllRecords();

OutputStream outputStream;
try {
outputStream = filipsContext.getContentResolver().openOutputStream(outputFileUri);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, "utf8"), 8192);

JSONArray arr = new JSONArray();
for(RecordAll record: records) {
for (RecordAll record : records) {
arr.put(record.toJSON());
}

bw.write(arr.toString());
//
// bw.write();
bw.flush();
bw.close();

} catch (IOException e) {
e.printStackTrace();
}
Expand Down

0 comments on commit ffd31c6

Please sign in to comment.