Moved CSVWriter and Configurable classes to core package

This commit is contained in:
Ziver Koc 2015-01-16 11:54:33 +01:00
parent 850dbb661b
commit 8a00a547cf
15 changed files with 216 additions and 203 deletions

View file

@ -4,6 +4,7 @@ import android.net.TrafficStats;
import android.os.Handler;
import com.ericsson.uecontrol.core.util.AbstractElementAdapter;
import com.ericsson.uecontrol.core.util.CSVWriter;
import com.ericsson.uecontrol.core.util.ThroughputCalculator;
import com.ericsson.uecontrol.gui.MainActivity;
import com.google.gson.Gson;
@ -29,7 +30,8 @@ public class UeControlExecutor implements Runnable{
private UeBehaviour currentlyActive;
private boolean terminate;
private Thread thread;
private Gson gson;
private String csvPath;
private CSVWriter csvLogger;
private Handler handler;
private ThroughputUpdateRunnable throughputUpdateRunnable;
@ -40,10 +42,6 @@ public class UeControlExecutor implements Runnable{
behaviours = new ArrayList<UeBehaviour>();
handler = new Handler();
throughputUpdateRunnable = new ThroughputUpdateRunnable();
gson = new GsonBuilder()
.registerTypeAdapter(UeBehaviour.class, new AbstractElementAdapter<UeBehaviour>())
.create();
}
public void addBehaviour(UeBehaviour b){
@ -51,6 +49,9 @@ public class UeControlExecutor implements Runnable{
}
public void read(String file) throws Exception {
Gson gson = new GsonBuilder()
.registerTypeAdapter(UeBehaviour.class, new AbstractElementAdapter<UeBehaviour>())
.create();
FileReader in = new FileReader(file);
Type type = new TypeToken<ArrayList<UeBehaviour>>(){}.getType();
ArrayList<UeBehaviour> newBehaviours = gson.fromJson(in, type);
@ -60,6 +61,9 @@ public class UeControlExecutor implements Runnable{
in.close();
}
public void save(String file) throws IOException {
Gson gson = new GsonBuilder()
.registerTypeAdapter(UeBehaviour.class, new AbstractElementAdapter<UeBehaviour>())
.create();
FileWriter out = new FileWriter(file);
Type type = new TypeToken<ArrayList<UeBehaviour>>(){}.getType();
log.debug("Saving behaviours: "+gson.toJson(behaviours, type));
@ -120,6 +124,8 @@ public class UeControlExecutor implements Runnable{
public void run(){
log.info("Starting execution");
if(csvPath != null)
csvLogger = new CSVWriter(csvPath);
while(!terminate) {
if(behaviours.isEmpty()) {
currentlyActive = null;
@ -147,12 +153,20 @@ public class UeControlExecutor implements Runnable{
currentlyActive = null;
}
}
if(csvLogger != null){
csvLogger.flush();
csvLogger = null;
}
log.info("Execution completed");
synchronized (thread){thread.notifyAll();}
}
/**
* Set the log path or null to disable logging
*/
public void setLogPath(String path){
csvPath = path;
}
public void setThroughputListener(ThroughputListener listener){
throughputListener = listener;
}
@ -163,10 +177,13 @@ public class UeControlExecutor implements Runnable{
public List<UeBehaviour> getBehaviourList() {
return behaviours;
}
public UeBehaviour getRunningBehaviour(){
return currentlyActive;
}
public CSVWriter getCsvLogger() {
return csvLogger;
}
public static interface ThroughputListener{
public void throughputUpdate(double downThroughput, double upThroughput);
@ -194,9 +211,16 @@ public class UeControlExecutor implements Runnable{
uploadSpeed.setHandledData(0);
downloadSpeed.setHandledData(0);
}
if (throughputListener != null && uploadSpeed.isUpdated())
throughputListener.throughputUpdate(downloadSpeed.getBitThroughput(), uploadSpeed.getBitThroughput());
if (uploadSpeed.isUpdated()) {
if(csvLogger != null)
csvLogger.write(getRunningBehaviour().getName(),
downloadSpeed.getBitThroughput(),
uploadSpeed.getBitThroughput());
if (throughputListener != null)
throughputListener.throughputUpdate(
downloadSpeed.getBitThroughput(),
uploadSpeed.getBitThroughput());
}
// Rescedule this handler
if(!terminate)
handler.postDelayed(this, 100);

View file

@ -2,7 +2,7 @@ package com.ericsson.uecontrol.core.behaviour;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.UrlUtil;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;

View file

@ -1,6 +1,6 @@
package com.ericsson.uecontrol.core.behaviour;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

View file

@ -1,7 +1,7 @@
package com.ericsson.uecontrol.core.behaviour;
import com.ericsson.uecontrol.core.util.ThroughputCalculator;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

View file

@ -10,7 +10,7 @@ import android.telephony.SmsManager;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.gui.MainActivity;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;

View file

@ -1,8 +1,7 @@
package com.ericsson.uecontrol.core.behaviour;
import android.util.Log;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;
/**

View file

@ -6,7 +6,7 @@ import android.telephony.TelephonyManager;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.CallUtil;
import com.ericsson.uecontrol.gui.MainActivity;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;

View file

@ -2,7 +2,7 @@ package com.ericsson.uecontrol.core.behaviour;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.core.util.UrlUtil;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;

View file

@ -3,7 +3,7 @@ package com.ericsson.uecontrol.core.behaviour;
import android.media.MediaPlayer;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.gui.util.Configurator.Configurable;
import com.ericsson.uecontrol.core.util.Configurator.Configurable;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;

View file

@ -1,4 +1,4 @@
package com.ericsson.uecontrol.gui.util;
package com.ericsson.uecontrol.core.util;
import android.content.Context;
import android.content.Intent;
@ -39,12 +39,9 @@ public class CSVWriter {
private File file;
private String comment;
public CSVWriter(){
Context context = MainActivity.getContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
public CSVWriter(String path){
comment = "";
String path = prefs.getString("logging_path", Environment.getExternalStorageDirectory().getAbsolutePath()+"/uecontrol/");
if(!path.endsWith(File.separator)) path += File.separator;
file = new File(
path,
@ -58,9 +55,7 @@ public class CSVWriter {
line.append(header).append(DELIMITER);
}
writeLine(line.toString());
// Add file to Media Scanner so it shows up when phone is connected with usb
MainActivity.getContext().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
flush();
}
public void addComment(String str){
@ -104,6 +99,11 @@ public class CSVWriter {
return false;
}
public void flush(){
// Add file to Media Scanner so it shows up when phone is connected with usb
MainActivity.getContext().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}
//******************* INFORMATION FUNCTIONS ********************************************
public static String getRat(){

View file

@ -1,130 +1,130 @@
package com.ericsson.uecontrol.gui.util;
import org.apache.log4j.Logger;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by ezivkoc on 2014-07-24.
*/
public class Configurator {
private static final Logger log = Logger.getLogger(Configurator.class);
/**
* Sets a field in a class as externally configurable.
*/
@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
@Target({ElementType.FIELD}) // This annotation can only be applied to class fields.
public static @interface Configurable{
/* Nice name of this parameter */
String value();
/* Defines the order the parameters, in ascending order */
int order() default Integer.MAX_VALUE;
}
public static enum ConfigType{
STRING, INT
}
private Object obj;
private ConfigurationParam[] params;
public Configurator(Object obj){
this.obj = obj;
this.params = getConfiguration(obj);
}
public ConfigurationParam[] getConfiguration(){
return params;
}
protected ConfigurationParam[] getConfiguration(Object obj){
Class c = obj.getClass();
ArrayList<ConfigurationParam> conf = new ArrayList<ConfigurationParam>();
Field[] all = c.getDeclaredFields();
for(Field f : all){
if(f.isAnnotationPresent(Configurable.class) &&
!Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())) {
try {
conf.add(new ConfigurationParam(f));
} catch (IllegalAccessException e) {
log.warn(null, e);
}
}
}
ConfigurationParam[] list = conf.toArray(new ConfigurationParam[conf.size()]);
Arrays.sort(list);
return list;
}
public void setConfiguration(){
for(ConfigurationParam param : params){
try {
param.set();
} catch (IllegalAccessException e) {
log.warn(null, e);
}
}
}
public class ConfigurationParam implements Comparable<ConfigurationParam>{
protected Field field;
protected String name;
protected String niceName;
protected ConfigType type;
protected Object value;
protected int order;
protected ConfigurationParam(Field f) throws IllegalAccessException {
field = f;
field.setAccessible(true);
name = field.getName();
niceName = field.getAnnotation(Configurable.class).value();
value = field.get(obj);
order = field.getAnnotation(Configurable.class).order();
if (f.getType() == String.class) type = ConfigType.STRING;
else if(f.getType() == int.class) type = ConfigType.INT;
}
public String getName(){return name;}
public String getNiceName(){return niceName;}
public ConfigType getType(){return type;}
public String getString(){
if(value == null)
return null;
return value.toString();}
public void setString(String v){
switch(type){
case STRING:
value = v; break;
case INT:
value = Integer.parseInt(v); break;
}
}
protected void set() throws IllegalAccessException {
field.set(obj, value);
}
@Override
public int compareTo(ConfigurationParam configurationParam) {
return this.order - configurationParam.order;
}
}
}
package com.ericsson.uecontrol.core.util;
import org.apache.log4j.Logger;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by ezivkoc on 2014-07-24.
*/
public class Configurator {
private static final Logger log = Logger.getLogger(Configurator.class);
/**
* Sets a field in a class as externally configurable.
*/
@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
@Target({ElementType.FIELD}) // This annotation can only be applied to class fields.
public static @interface Configurable{
/* Nice name of this parameter */
String value();
/* Defines the order the parameters, in ascending order */
int order() default Integer.MAX_VALUE;
}
public static enum ConfigType{
STRING, INT
}
private Object obj;
private ConfigurationParam[] params;
public Configurator(Object obj){
this.obj = obj;
this.params = getConfiguration(obj);
}
public ConfigurationParam[] getConfiguration(){
return params;
}
protected ConfigurationParam[] getConfiguration(Object obj){
Class c = obj.getClass();
ArrayList<ConfigurationParam> conf = new ArrayList<ConfigurationParam>();
Field[] all = c.getDeclaredFields();
for(Field f : all){
if(f.isAnnotationPresent(Configurable.class) &&
!Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())) {
try {
conf.add(new ConfigurationParam(f));
} catch (IllegalAccessException e) {
log.warn(null, e);
}
}
}
ConfigurationParam[] list = conf.toArray(new ConfigurationParam[conf.size()]);
Arrays.sort(list);
return list;
}
public void setConfiguration(){
for(ConfigurationParam param : params){
try {
param.set();
} catch (IllegalAccessException e) {
log.warn(null, e);
}
}
}
public class ConfigurationParam implements Comparable<ConfigurationParam>{
protected Field field;
protected String name;
protected String niceName;
protected ConfigType type;
protected Object value;
protected int order;
protected ConfigurationParam(Field f) throws IllegalAccessException {
field = f;
field.setAccessible(true);
name = field.getName();
niceName = field.getAnnotation(Configurable.class).value();
value = field.get(obj);
order = field.getAnnotation(Configurable.class).order();
if (f.getType() == String.class) type = ConfigType.STRING;
else if(f.getType() == int.class) type = ConfigType.INT;
}
public String getName(){return name;}
public String getNiceName(){return niceName;}
public ConfigType getType(){return type;}
public String getString(){
if(value == null)
return null;
return value.toString();}
public void setString(String v){
switch(type){
case STRING:
value = v; break;
case INT:
value = Integer.parseInt(v); break;
}
}
protected void set() throws IllegalAccessException {
field.set(obj, value);
}
@Override
public int compareTo(ConfigurationParam configurationParam) {
return this.order - configurationParam.order;
}
}
}

View file

@ -1,4 +1,4 @@
package com.ericsson.uecontrol.gui.util;
package com.ericsson.uecontrol.core.util;
import android.content.BroadcastReceiver;
import android.content.Context;

View file

@ -6,6 +6,7 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
@ -23,7 +24,6 @@ import com.ericsson.uecontrol.gui.fragments.ExecNotification;
import com.ericsson.uecontrol.gui.fragments.FileBrowserDialog;
import com.ericsson.uecontrol.gui.fragments.FileBrowserDialog.OnFileSelectionListener;
import com.ericsson.uecontrol.gui.fragments.StatusFragment;
import com.ericsson.uecontrol.gui.util.CSVWriter;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
@ -48,8 +48,7 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
private boolean backButtonPressed = false;
/* Static Data */
private static UeControlExecutor currentExecutor;
private static CSVWriter csvLogger;
private static UeControlExecutor executor;
private static int uid;
private static Context context;
@ -70,24 +69,24 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
setupDebugLogging();
// Setup Executor
if(currentExecutor == null) {
if(executor == null) {
log.info("Creating new instance of executor");
currentExecutor = new UeControlExecutor();
currentExecutor.setDeviceBasedThroughput(Boolean.parseBoolean(prefs.getString("throughput_type", "false")));
executor = new UeControlExecutor();
executor.setDeviceBasedThroughput(Boolean.parseBoolean(prefs.getString("throughput_type", "false")));
File input = new File(this.getFilesDir(), BEHAVIOUR_SAVE_FILE);
if (input.exists()) {
try {
log.debug("Reading saved state");
currentExecutor.read(input.getAbsolutePath());
executor.read(input.getAbsolutePath());
} catch (Exception e) {
Toast.makeText(this, "Unable to load saved state", Toast.LENGTH_SHORT).show();
log.error(null, e);
}
} else {
log.debug("No saved state found, creating default behaviours");
currentExecutor.addBehaviour(new UeBehaviourSleep());
currentExecutor.addBehaviour(new UeBehaviourSurfing());
currentExecutor.addBehaviour(new UeBehaviourSleep(4000));
executor.addBehaviour(new UeBehaviourSleep());
executor.addBehaviour(new UeBehaviourSurfing());
executor.addBehaviour(new UeBehaviourSleep(4000));
}
}
else {
@ -103,7 +102,7 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
getFragmentManager().findFragmentById(R.id.behaviour_list_fragment);
currentExecutor.setThroughputListener(statusFragment.getThroughputListener());
executor.setThroughputListener(statusFragment.getThroughputListener());
updateExecutionState();
}
@ -137,8 +136,8 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
}
else if(key.equals("throughput_type")){
log.info("Device Throughput set to: "+sharedPreferences.getString("throughput_type", "false"));
if(currentExecutor != null)
currentExecutor.setDeviceBasedThroughput(Boolean.parseBoolean(sharedPreferences.getString("throughput_type", "false")));
if(executor != null)
executor.setDeviceBasedThroughput(Boolean.parseBoolean(sharedPreferences.getString("throughput_type", "false")));
}
}
@ -168,37 +167,36 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_execute) {
if(currentExecutor.isRunning()) {
currentExecutor.terminate();
csvLogger = null;
if(executor.isRunning()) {
executor.terminate();
}
else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("logging", true))
csvLogger = new CSVWriter();
if(prefs.getBoolean("logging", false))
executor.setLogPath(prefs.getString("logging_path",
Environment.getExternalStorageDirectory().getAbsolutePath()+"/uecontrol/"));
else
csvLogger = null;
currentExecutor.execute();
executor.setLogPath(null);
executor.execute();
}
updateExecutionState();
return true;
}
else if (id == R.id.action_mark) {
if(csvLogger != null) {
csvLogger.addComment("--- Mark ---");
if (executor.getCsvLogger() != null) {
executor.getCsvLogger().addComment("--- Mark ---");
Toast.makeText(this, "Mark added to log", Toast.LENGTH_SHORT).show();
}
}
else if (id == R.id.action_reset) {
if(currentExecutor != null)
currentExecutor.reset();
if(executor != null)
executor.reset();
if(statusFragment != null)
statusFragment.reset();
csvLogger = null;
updateExecutionState();
}
else if (id == R.id.action_edit) {
if(!currentExecutor.isRunning()) {
if(!executor.isRunning()) {
Intent intent = new Intent(this, EditActivity.class);
startActivity(intent);
}
@ -225,12 +223,12 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
public void onFileSelection(String tag, File file){
try {
if(tag.equals("import")) {
currentExecutor.read(file.getAbsolutePath());
executor.read(file.getAbsolutePath());
if(behaviourListFragment != null)
behaviourListFragment.onResume();
}
else if(tag.equals("export")) {
currentExecutor.save(file.getAbsolutePath());
executor.save(file.getAbsolutePath());
}
} catch (Exception e) {
String msg = "Unable to import from file";
@ -245,10 +243,10 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
private void updateExecutionState(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(action_execute != null) {
if (currentExecutor.isRunning()) {
if (executor.isRunning()) {
action_execute.setTitle(R.string.action_stop);
ExecNotification.create();
if(action_mark != null && csvLogger != null)
if(action_mark != null && prefs.getBoolean("logging", false))
action_mark.setEnabled(true);
if(prefs.getBoolean("screen_on", false))
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
@ -266,9 +264,9 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
@Override
public void onBackPressed() {
if (backButtonPressed) {
if(currentExecutor != null){
if(executor != null){
log.info("Terminating executor");
currentExecutor.terminate();
executor.terminate();
}
super.onBackPressed();
return;
@ -286,15 +284,8 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
}
public static void logThroughput(double downThroughput, double upThroughput) {
if(csvLogger == null || currentExecutor == null || currentExecutor.getRunningBehaviour() == null)
return;
csvLogger.write(currentExecutor.getRunningBehaviour().getName(), downThroughput, upThroughput);
}
public static UeControlExecutor getExecutor() {
return currentExecutor;
return executor;
}
public static int getUID(){
return uid;

View file

@ -15,8 +15,8 @@ import android.widget.TextView;
import com.ericsson.uecontrol.R;
import com.ericsson.uecontrol.core.UeBehaviour;
import com.ericsson.uecontrol.gui.MainActivity;
import com.ericsson.uecontrol.gui.util.Configurator;
import com.ericsson.uecontrol.gui.util.Configurator.ConfigurationParam;
import com.ericsson.uecontrol.core.util.Configurator;
import com.ericsson.uecontrol.core.util.Configurator.ConfigurationParam;
import java.util.HashMap;

View file

@ -16,7 +16,7 @@ import com.ericsson.uecontrol.R;
import com.ericsson.uecontrol.core.UeControlExecutor;
import com.ericsson.uecontrol.core.util.ThroughputCalculator;
import com.ericsson.uecontrol.gui.MainActivity;
import com.ericsson.uecontrol.gui.util.CSVWriter;
import com.ericsson.uecontrol.core.util.CSVWriter;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle;
@ -96,7 +96,6 @@ public class StatusFragment extends Fragment {
upGraph.appendData(new GraphViewData(x, upThroughput), true, 120);
x++;
MainActivity.logThroughput(downThroughput, upThroughput);
ExecNotification.update(downThroughput, upThroughput);
startActivityTimer();
}