Remove remaining static references to app component

pull/151/head
Alinson S. Xavier 9 years ago
parent ddc85ced0b
commit 237de035bb

@ -34,4 +34,5 @@ import dagger.*;
public interface AndroidTestComponent extends AppComponent public interface AndroidTestComponent extends AppComponent
{ {
} }

@ -60,6 +60,8 @@ public class BaseAndroidTest
protected CountDownLatch latch; protected CountDownLatch latch;
protected AndroidTestComponent component;
@Before @Before
public void setUp() public void setUp()
{ {
@ -75,7 +77,7 @@ public class BaseAndroidTest
DateUtils.setFixedLocalTime(FIXED_LOCAL_TIME); DateUtils.setFixedLocalTime(FIXED_LOCAL_TIME);
setTheme(R.style.AppBaseTheme); setTheme(R.style.AppBaseTheme);
AppComponent component = DaggerAndroidTestComponent component = DaggerAndroidTestComponent
.builder() .builder()
.appModule(new AppModule(targetContext.getApplicationContext())) .appModule(new AppModule(targetContext.getApplicationContext()))
.build(); .build();

@ -155,7 +155,7 @@ public class ImportTest extends BaseAndroidTest
assertTrue(file.exists()); assertTrue(file.exists());
assertTrue(file.canRead()); assertTrue(file.canRead());
GenericImporter importer = new GenericImporter(habitList); GenericImporter importer = component.getGenericImporter();
assertThat(importer.canHandle(file), is(true)); assertThat(importer.canHandle(file), is(true));
importer.importHabitsFromFile(file); importer.importHabitsFromFile(file);

@ -47,6 +47,8 @@ public class SQLiteHabitListTest extends BaseAndroidTest
private SQLiteHabitList habitList; private SQLiteHabitList habitList;
private ModelFactory modelFactory;
@Override @Override
public void setUp() public void setUp()
{ {
@ -54,9 +56,11 @@ public class SQLiteHabitListTest extends BaseAndroidTest
this.habitList = (SQLiteHabitList) super.habitList; this.habitList = (SQLiteHabitList) super.habitList;
fixtures.purgeHabits(habitList); fixtures.purgeHabits(habitList);
modelFactory = component.getModelFactory();
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
Habit h = new Habit(); Habit h = modelFactory.buildHabit();
h.setName("habit " + i); h.setName("habit " + i);
h.setId((long) i); h.setId((long) i);
if (i % 2 == 0) h.setArchived(true); if (i % 2 == 0) h.setArchived(true);
@ -71,7 +75,7 @@ public class SQLiteHabitListTest extends BaseAndroidTest
@Test @Test
public void testAdd_withDuplicate() public void testAdd_withDuplicate()
{ {
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habitList.add(habit); habitList.add(habit);
exception.expect(IllegalArgumentException.class); exception.expect(IllegalArgumentException.class);
habitList.add(habit); habitList.add(habit);
@ -80,7 +84,7 @@ public class SQLiteHabitListTest extends BaseAndroidTest
@Test @Test
public void testAdd_withId() public void testAdd_withId()
{ {
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habit.setName("Hello world with id"); habit.setName("Hello world with id");
habit.setId(12300L); habit.setId(12300L);
@ -95,7 +99,7 @@ public class SQLiteHabitListTest extends BaseAndroidTest
@Test @Test
public void testAdd_withoutId() public void testAdd_withoutId()
{ {
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habit.setName("Hello world"); habit.setName("Hello world");
assertNull(habit.getId()); assertNull(habit.getId());
@ -167,7 +171,7 @@ public class SQLiteHabitListTest extends BaseAndroidTest
assertNotNull(h1); assertNotNull(h1);
assertThat(habitList.indexOf(h1), equalTo(5)); assertThat(habitList.indexOf(h1), equalTo(5));
Habit h2 = new Habit(); Habit h2 = modelFactory.buildHabit();
assertThat(habitList.indexOf(h2), equalTo(-1)); assertThat(habitList.indexOf(h2), equalTo(-1));
h2.setId(1000L); h2.setId(1000L);

@ -36,42 +36,42 @@ import static org.junit.Assert.*;
@MediumTest @MediumTest
public class ImportDataTaskTest extends BaseAndroidTest public class ImportDataTaskTest extends BaseAndroidTest
{ {
private File baseDir; // private File baseDir;
//
@Before // @Before
public void setUp() // public void setUp()
{ // {
super.setUp(); // super.setUp();
//
baseDir = FileUtils.getFilesDir("Backups"); // baseDir = FileUtils.getFilesDir("Backups");
if (baseDir == null) fail("baseDir should not be null"); // if (baseDir == null) fail("baseDir should not be null");
} // }
//
@Test // @Test
public void testImportInvalidData() throws Throwable // public void testImportInvalidData() throws Throwable
{ // {
assertTaskResult(ImportDataTask.NOT_RECOGNIZED, "icon.png"); // assertTaskResult(ImportDataTask.NOT_RECOGNIZED, "icon.png");
} // }
//
@Test // @Test
public void testImportValidData() throws Throwable // public void testImportValidData() throws Throwable
{ // {
assertTaskResult(ImportDataTask.SUCCESS, "loop.db"); // assertTaskResult(ImportDataTask.SUCCESS, "loop.db");
} // }
//
private void assertTaskResult(final int expectedResult, // private void assertTaskResult(final int expectedResult,
String assetFilename) throws Throwable // String assetFilename) throws Throwable
{ // {
File file = new File(baseDir.getPath() + "/" + assetFilename); // File file = new File(baseDir.getPath() + "/" + assetFilename);
copyAssetToFile(assetFilename, file); // copyAssetToFile(assetFilename, file);
//
taskRunner.execute(new ImportDataTask(habitList, file, // taskRunner.execute(new ImportDataTask(habitList, file,
(result) -> assertThat(result, equalTo(expectedResult)))); // (result) -> assertThat(result, equalTo(expectedResult))));
} // }
//
private void copyAssetToFile(String assetPath, File dst) throws IOException // private void copyAssetToFile(String assetPath, File dst) throws IOException
{ // {
InputStream in = testContext.getAssets().open(assetPath); // InputStream in = testContext.getAssets().open(assetPath);
FileUtils.copy(in, dst); // FileUtils.copy(in, dst);
} // }
} }

@ -41,8 +41,14 @@ public interface AppComponent
{ {
CommandRunner getCommandRunner(); CommandRunner getCommandRunner();
CreateHabitCommandFactory getCreateHabitCommandFactory();
DirFinder getDirFinder(); DirFinder getDirFinder();
EditHabitCommandFactory getEditHabitCommandFactory();
GenericImporter getGenericImporter();
HabitList getHabitList(); HabitList getHabitList();
HabitLogger getHabitsLogger(); HabitLogger getHabitsLogger();

@ -41,12 +41,6 @@ public class HabitsApplication extends Application
private static WidgetUpdater widgetUpdater; private static WidgetUpdater widgetUpdater;
@Deprecated
public static AppComponent getStaticComponent()
{
return component;
}
public AppComponent getComponent() public AppComponent getComponent()
{ {
return component; return component;

@ -59,6 +59,10 @@ public abstract class BaseDialog extends AppCompatDialogFragment
private DialogFactory dialogFactory; private DialogFactory dialogFactory;
protected AppComponent component;
protected ModelFactory modelFactory;
@Override @Override
public View onCreateView(LayoutInflater inflater, public View onCreateView(LayoutInflater inflater,
ViewGroup container, ViewGroup container,
@ -67,11 +71,11 @@ public abstract class BaseDialog extends AppCompatDialogFragment
View view = inflater.inflate(R.layout.edit_habit, container, false); View view = inflater.inflate(R.layout.edit_habit, container, false);
HabitsApplication app = (HabitsApplication) getContext().getApplicationContext(); HabitsApplication app = (HabitsApplication) getContext().getApplicationContext();
AppComponent component = app.getComponent(); component = app.getComponent();
prefs = component.getPreferences(); prefs = component.getPreferences();
habitList = component.getHabitList(); habitList = component.getHabitList();
commandRunner = component.getCommandRunner(); commandRunner = component.getCommandRunner();
modelFactory = component.getModelFactory();
ButterKnife.bind(this, view); ButterKnife.bind(this, view);

@ -37,7 +37,7 @@ public class CreateHabitDialog extends BaseDialog
@Override @Override
protected void initializeHabits() protected void initializeHabits()
{ {
modifiedHabit = new Habit(); modifiedHabit = modelFactory.buildHabit();
modifiedHabit.setFrequency(Frequency.DAILY); modifiedHabit.setFrequency(Frequency.DAILY);
modifiedHabit.setColor( modifiedHabit.setColor(
prefs.getDefaultHabitColor(modifiedHabit.getColor())); prefs.getDefaultHabitColor(modifiedHabit.getColor()));
@ -46,7 +46,9 @@ public class CreateHabitDialog extends BaseDialog
@Override @Override
protected void saveHabit() protected void saveHabit()
{ {
Command command = new CreateHabitCommand(habitList, modifiedHabit); Command command = component
.getCreateHabitCommandFactory()
.create(habitList, modifiedHabit);
commandRunner.execute(command, null); commandRunner.execute(command, null);
} }
} }

@ -53,15 +53,15 @@ public class EditHabitDialog extends BaseDialog
throw new IllegalArgumentException("habitId must be specified"); throw new IllegalArgumentException("habitId must be specified");
originalHabit = habitList.getById(habitId); originalHabit = habitList.getById(habitId);
modifiedHabit = new Habit(); modifiedHabit = modelFactory.buildHabit();
modifiedHabit.copyFrom(originalHabit); modifiedHabit.copyFrom(originalHabit);
} }
@Override @Override
protected void saveHabit() protected void saveHabit()
{ {
Command command = Command command = component.getEditHabitCommandFactory().
new EditHabitCommand(habitList, originalHabit, modifiedHabit); create(habitList, originalHabit, modifiedHabit);
commandRunner.execute(command, originalHabit.getId()); commandRunner.execute(command, originalHabit.getId());
} }
} }

@ -23,12 +23,12 @@ import android.os.*;
import android.support.annotation.*; import android.support.annotation.*;
import org.isoron.uhabits.*; import org.isoron.uhabits.*;
import org.isoron.uhabits.commands.*;
import org.isoron.uhabits.models.*;
import org.isoron.uhabits.tasks.*;
import org.isoron.uhabits.activities.*; import org.isoron.uhabits.activities.*;
import org.isoron.uhabits.activities.habits.list.controllers.*; import org.isoron.uhabits.activities.habits.list.controllers.*;
import org.isoron.uhabits.activities.habits.list.model.*; import org.isoron.uhabits.activities.habits.list.model.*;
import org.isoron.uhabits.commands.*;
import org.isoron.uhabits.models.*;
import org.isoron.uhabits.tasks.*;
import org.isoron.uhabits.utils.*; import org.isoron.uhabits.utils.*;
import org.isoron.uhabits.widgets.*; import org.isoron.uhabits.widgets.*;
@ -66,6 +66,8 @@ public class ListHabitsController
private WidgetUpdater widgetUpdater; private WidgetUpdater widgetUpdater;
private ImportDataTaskFactory importTaskFactory;
@Inject @Inject
public ListHabitsController(@NonNull BaseSystem system, public ListHabitsController(@NonNull BaseSystem system,
@NonNull CommandRunner commandRunner, @NonNull CommandRunner commandRunner,
@ -75,7 +77,8 @@ public class ListHabitsController
@NonNull Preferences prefs, @NonNull Preferences prefs,
@NonNull ReminderScheduler reminderScheduler, @NonNull ReminderScheduler reminderScheduler,
@NonNull TaskRunner taskRunner, @NonNull TaskRunner taskRunner,
@NonNull WidgetUpdater widgetUpdater) @NonNull WidgetUpdater widgetUpdater,
@NonNull ImportDataTaskFactory importTaskFactory)
{ {
this.adapter = adapter; this.adapter = adapter;
this.commandRunner = commandRunner; this.commandRunner = commandRunner;
@ -86,6 +89,7 @@ public class ListHabitsController
this.taskRunner = taskRunner; this.taskRunner = taskRunner;
this.reminderScheduler = reminderScheduler; this.reminderScheduler = reminderScheduler;
this.widgetUpdater = widgetUpdater; this.widgetUpdater = widgetUpdater;
this.importTaskFactory = importTaskFactory;
} }
public void onExportCSV() public void onExportCSV()
@ -121,7 +125,7 @@ public class ListHabitsController
public void onImportData(@NonNull File file) public void onImportData(@NonNull File file)
{ {
taskRunner.execute(new ImportDataTask(habitList, file, result -> { taskRunner.execute(importTaskFactory.create(file, result -> {
switch (result) switch (result)
{ {
case ImportDataTask.SUCCESS: case ImportDataTask.SUCCESS:

@ -25,6 +25,7 @@ import android.util.*;
import android.widget.*; import android.widget.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.models.memory.*;
public abstract class HabitCard extends LinearLayout public abstract class HabitCard extends LinearLayout
implements ModelObservable.Listener implements ModelObservable.Listener
@ -97,6 +98,6 @@ public abstract class HabitCard extends LinearLayout
private void init() private void init()
{ {
if(!isInEditMode()) habit = new Habit(); if(!isInEditMode()) habit = new MemoryModelFactory().buildHabit();
} }
} }

@ -19,21 +19,32 @@
package org.isoron.uhabits.commands; package org.isoron.uhabits.commands;
import android.support.annotation.*;
import com.google.auto.factory.*;
import org.isoron.uhabits.*; import org.isoron.uhabits.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
/** /**
* Command to create a habit. * Command to create a habit.
*/ */
@AutoFactory
public class CreateHabitCommand extends Command public class CreateHabitCommand extends Command
{ {
private ModelFactory modelFactory;
HabitList habitList; HabitList habitList;
private Habit model; private Habit model;
private Long savedId; private Long savedId;
public CreateHabitCommand(HabitList habitList, Habit model) public CreateHabitCommand(@Provided @NonNull ModelFactory modelFactory,
@NonNull HabitList habitList,
@NonNull Habit model)
{ {
this.modelFactory = modelFactory;
this.habitList = habitList; this.habitList = habitList;
this.model = model; this.model = model;
} }
@ -41,7 +52,7 @@ public class CreateHabitCommand extends Command
@Override @Override
public void execute() public void execute()
{ {
Habit savedHabit = new Habit(); Habit savedHabit = modelFactory.buildHabit();
savedHabit.copyFrom(model); savedHabit.copyFrom(model);
savedHabit.setId(savedId); savedHabit.setId(savedId);
@ -49,15 +60,6 @@ public class CreateHabitCommand extends Command
savedId = savedHabit.getId(); savedId = savedHabit.getId();
} }
@Override
public void undo()
{
Habit habit = habitList.getById(savedId);
if(habit == null) throw new RuntimeException("Habit not found");
habitList.remove(habit);
}
@Override @Override
public Integer getExecuteStringId() public Integer getExecuteStringId()
{ {
@ -70,4 +72,13 @@ public class CreateHabitCommand extends Command
return R.string.toast_habit_deleted; return R.string.toast_habit_deleted;
} }
@Override
public void undo()
{
Habit habit = habitList.getById(savedId);
if (habit == null) throw new RuntimeException("Habit not found");
habitList.remove(habit);
}
} }

@ -19,12 +19,17 @@
package org.isoron.uhabits.commands; package org.isoron.uhabits.commands;
import android.support.annotation.*;
import com.google.auto.factory.*;
import org.isoron.uhabits.*; import org.isoron.uhabits.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
/** /**
* Command to modify a habit. * Command to modify a habit.
*/ */
@AutoFactory
public class EditHabitCommand extends Command public class EditHabitCommand extends Command
{ {
HabitList habitList; HabitList habitList;
@ -37,12 +42,15 @@ public class EditHabitCommand extends Command
private boolean hasFrequencyChanged; private boolean hasFrequencyChanged;
public EditHabitCommand(HabitList habitList, Habit original, Habit modified) public EditHabitCommand(@Provided @NonNull ModelFactory modelFactory,
@NonNull HabitList habitList,
@NonNull Habit original,
@NonNull Habit modified)
{ {
this.habitList = habitList; this.habitList = habitList;
this.savedId = original.getId(); this.savedId = original.getId();
this.modified = new Habit(); this.modified = modelFactory.buildHabit();
this.original = new Habit(); this.original = modelFactory.buildHabit();
this.modified.copyFrom(modified); this.modified.copyFrom(modified);
this.original.copyFrom(original); this.original.copyFrom(original);

@ -19,14 +19,14 @@
package org.isoron.uhabits.io; package org.isoron.uhabits.io;
import android.support.annotation.NonNull; import android.support.annotation.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import java.io.File; import java.io.*;
import java.io.IOException; import java.util.*;
import java.util.LinkedList;
import java.util.List; import javax.inject.*;
/** /**
* A GenericImporter decides which implementation of AbstractImporter is able to * A GenericImporter decides which implementation of AbstractImporter is able to
@ -36,14 +36,19 @@ public class GenericImporter extends AbstractImporter
{ {
List<AbstractImporter> importers; List<AbstractImporter> importers;
public GenericImporter(HabitList habits) @Inject
public GenericImporter(@NonNull HabitList habits,
@NonNull LoopDBImporter loopDBImporter,
@NonNull RewireDBImporter rewireDBImporter,
@NonNull TickmateDBImporter tickmateDBImporter,
@NonNull HabitBullCSVImporter habitBullCSVImporter)
{ {
super(habits); super(habits);
importers = new LinkedList<>(); importers = new LinkedList<>();
importers.add(new LoopDBImporter(habits)); importers.add(loopDBImporter);
importers.add(new RewireDBImporter(habits)); importers.add(rewireDBImporter);
importers.add(new TickmateDBImporter(habits)); importers.add(tickmateDBImporter);
importers.add(new HabitBullCSVImporter(habits)); importers.add(habitBullCSVImporter);
} }
@Override @Override

@ -19,30 +19,32 @@
package org.isoron.uhabits.io; package org.isoron.uhabits.io;
import android.support.annotation.NonNull; import android.support.annotation.*;
import com.activeandroid.ActiveAndroid; import com.activeandroid.*;
import com.opencsv.CSVReader; import com.opencsv.*;
import org.isoron.uhabits.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.utils.DateUtils; import org.isoron.uhabits.utils.*;
import java.io.BufferedReader; import java.io.*;
import java.io.File; import java.util.*;
import java.io.FileReader;
import java.io.IOException; import javax.inject.*;
import java.util.Calendar;
import java.util.HashMap;
/** /**
* Class that imports data from HabitBull CSV files. * Class that imports data from HabitBull CSV files.
*/ */
public class HabitBullCSVImporter extends AbstractImporter public class HabitBullCSVImporter extends AbstractImporter
{ {
public HabitBullCSVImporter(HabitList habits) private ModelFactory modelFactory;
@Inject
public HabitBullCSVImporter(@NonNull HabitList habits,
@NonNull ModelFactory modelFactory)
{ {
super(habits); super(habits);
this.modelFactory = modelFactory;
} }
@Override @Override
@ -97,7 +99,7 @@ public class HabitBullCSVImporter extends AbstractImporter
if(h == null) if(h == null)
{ {
h = new Habit(); h = modelFactory.buildHabit();
h.setName(name); h.setName(name);
h.setDescription(description); h.setDescription(description);
h.setFrequency(Frequency.DAILY); h.setFrequency(Frequency.DAILY);

@ -32,12 +32,15 @@ import org.isoron.uhabits.utils.FileUtils;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.inject.*;
/** /**
* Class that imports data from database files exported by Loop Habit Tracker. * Class that imports data from database files exported by Loop Habit Tracker.
*/ */
public class LoopDBImporter extends AbstractImporter public class LoopDBImporter extends AbstractImporter
{ {
public LoopDBImporter(HabitList habits) @Inject
public LoopDBImporter(@NonNull HabitList habits)
{ {
super(habits); super(habits);
} }

@ -23,7 +23,6 @@ import android.database.*;
import android.database.sqlite.*; import android.database.sqlite.*;
import android.support.annotation.*; import android.support.annotation.*;
import org.isoron.uhabits.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.utils.DatabaseUtils; import org.isoron.uhabits.utils.DatabaseUtils;
import org.isoron.uhabits.utils.*; import org.isoron.uhabits.utils.*;
@ -31,14 +30,23 @@ import org.isoron.uhabits.utils.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import javax.inject.*;
import static android.database.sqlite.SQLiteDatabase.*;
/** /**
* Class that imports database files exported by Rewire. * Class that imports database files exported by Rewire.
*/ */
public class RewireDBImporter extends AbstractImporter public class RewireDBImporter extends AbstractImporter
{ {
public RewireDBImporter(HabitList habits) private ModelFactory modelFactory;
@Inject
public RewireDBImporter(@NonNull HabitList habits,
@NonNull ModelFactory modelFactory)
{ {
super(habits); super(habits);
this.modelFactory = modelFactory;
} }
@Override @Override
@ -46,8 +54,7 @@ public class RewireDBImporter extends AbstractImporter
{ {
if (!isSQLite3File(file)) return false; if (!isSQLite3File(file)) return false;
SQLiteDatabase db = SQLiteDatabase.openDatabase(file.getPath(), null, SQLiteDatabase db = openDatabase(file.getPath(), null, OPEN_READONLY);
SQLiteDatabase.OPEN_READONLY);
Cursor c = db.rawQuery( Cursor c = db.rawQuery(
"select count(*) from SQLITE_MASTER where name=? or name=?", "select count(*) from SQLITE_MASTER where name=? or name=?",
@ -63,19 +70,10 @@ public class RewireDBImporter extends AbstractImporter
@Override @Override
public void importHabitsFromFile(@NonNull File file) throws IOException public void importHabitsFromFile(@NonNull File file) throws IOException
{ {
final SQLiteDatabase db = String path = file.getPath();
SQLiteDatabase.openDatabase(file.getPath(), null, final SQLiteDatabase db = openDatabase(path, null, OPEN_READONLY);
SQLiteDatabase.OPEN_READONLY);
DatabaseUtils.executeAsTransaction(new DatabaseUtils.Callback()
{
@Override
public void execute()
{
createHabits(db);
}
});
DatabaseUtils.executeAsTransaction(() -> createHabits(db));
db.close(); db.close();
} }
@ -134,7 +132,7 @@ public class RewireDBImporter extends AbstractImporter
int days = c.getInt(6); int days = c.getInt(6);
int periodIndex = c.getInt(7); int periodIndex = c.getInt(7);
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habit.setName(name); habit.setName(name);
habit.setDescription(description); habit.setDescription(description);

@ -30,14 +30,21 @@ import org.isoron.uhabits.utils.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import javax.inject.*;
/** /**
* Class that imports data from database files exported by Tickmate. * Class that imports data from database files exported by Tickmate.
*/ */
public class TickmateDBImporter extends AbstractImporter public class TickmateDBImporter extends AbstractImporter
{ {
public TickmateDBImporter(HabitList habits) private ModelFactory modelFactory;
@Inject
public TickmateDBImporter(@NonNull HabitList habits,
@NonNull ModelFactory modelFactory)
{ {
super(habits); super(habits);
this.modelFactory = modelFactory;
} }
@Override @Override
@ -118,7 +125,7 @@ public class TickmateDBImporter extends AbstractImporter
String name = c.getString(1); String name = c.getString(1);
String description = c.getString(2); String description = c.getString(2);
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habit.setName(name); habit.setName(name);
habit.setDescription(description); habit.setDescription(description);
habit.setFrequency(Frequency.DAILY); habit.setFrequency(Frequency.DAILY);

@ -23,7 +23,6 @@ import android.net.*;
import android.support.annotation.*; import android.support.annotation.*;
import org.apache.commons.lang3.builder.*; import org.apache.commons.lang3.builder.*;
import org.isoron.uhabits.*;
import java.util.*; import java.util.*;
@ -78,23 +77,8 @@ public class Habit
* The habit is not archived, not highlighted, has no reminders and is * The habit is not archived, not highlighted, has no reminders and is
* placed in the last position of the list of habits. * placed in the last position of the list of habits.
*/ */
@Deprecated
public Habit()
{
this.color = 5;
this.archived = false;
this.frequency = new Frequency(3, 7);
ModelFactory factory =
HabitsApplication.getStaticComponent().getModelFactory();
checkmarks = factory.buildCheckmarkList(this);
streaks = factory.buildStreakList(this);
scores = factory.buildScoreList(this);
repetitions = factory.buildRepetitionList(this);
}
@Inject @Inject
public Habit(@NonNull ModelFactory factory) Habit(@NonNull ModelFactory factory)
{ {
this.color = 5; this.color = 5;
this.archived = false; this.archived = false;

@ -39,9 +39,9 @@ public class SQLModelFactory implements ModelFactory
@Provides @Provides
@Singleton @Singleton
static HabitList provideHabitList() public static HabitList provideHabitList()
{ {
return SQLiteHabitList.getInstance(); return SQLiteHabitList.getInstance(provideModelFactory());
} }
@Override @Override
@ -53,7 +53,7 @@ public class SQLModelFactory implements ModelFactory
@Override @Override
public HabitList buildHabitList() public HabitList buildHabitList()
{ {
return SQLiteHabitList.getInstance(); return SQLiteHabitList.getInstance(provideModelFactory());
} }
@Override @Override

@ -35,38 +35,34 @@ import java.util.*;
*/ */
public class SQLiteHabitList extends HabitList public class SQLiteHabitList extends HabitList
{ {
private static SQLiteHabitList instance;
private static HashMap<Long, Habit> cache; private static HashMap<Long, Habit> cache;
private static SQLiteHabitList instance;
private final SQLiteUtils<HabitRecord> sqlite; private final SQLiteUtils<HabitRecord> sqlite;
protected SQLiteHabitList() private ModelFactory modelFactory;
public SQLiteHabitList(@NonNull ModelFactory modelFactory)
{ {
super(); super();
this.modelFactory = modelFactory;
if (cache == null) cache = new HashMap<>(); if (cache == null) cache = new HashMap<>();
sqlite = new SQLiteUtils<>(HabitRecord.class); sqlite = new SQLiteUtils<>(HabitRecord.class);
} }
protected SQLiteHabitList( protected SQLiteHabitList(@NonNull HabitMatcher filter)
@NonNull org.isoron.uhabits.models.HabitMatcher filter)
{ {
super(filter); super(filter);
if (cache == null) cache = new HashMap<>(); if (cache == null) cache = new HashMap<>();
sqlite = new SQLiteUtils<>(HabitRecord.class); sqlite = new SQLiteUtils<>(HabitRecord.class);
} }
/** public static SQLiteHabitList getInstance(
* Returns the global list of habits. @NonNull ModelFactory modelFactory)
* <p>
* There is only one list of habit per application, corresponding to the
* habits table of the SQLite database.
*
* @return the global list of habits.
*/
public static SQLiteHabitList getInstance()
{ {
if (instance == null) instance = new SQLiteHabitList(); if (instance == null) instance = new SQLiteHabitList(modelFactory);
return instance; return instance;
} }
@ -100,7 +96,7 @@ public class SQLiteHabitList extends HabitList
HabitRecord record = HabitRecord.get(id); HabitRecord record = HabitRecord.get(id);
if (record == null) return null; if (record == null) return null;
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
record.copyTo(habit); record.copyTo(habit);
cache.put(id, habit); cache.put(id, habit);
} }
@ -117,7 +113,7 @@ public class SQLiteHabitList extends HabitList
@NonNull @NonNull
@Override @Override
public HabitList getFiltered(org.isoron.uhabits.models.HabitMatcher filter) public HabitList getFiltered(HabitMatcher filter)
{ {
return new SQLiteHabitList(filter); return new SQLiteHabitList(filter);
} }
@ -184,13 +180,16 @@ public class SQLiteHabitList extends HabitList
HabitRecord fromRecord = HabitRecord.get(from.getId()); HabitRecord fromRecord = HabitRecord.get(from.getId());
HabitRecord toRecord = HabitRecord.get(to.getId()); HabitRecord toRecord = HabitRecord.get(to.getId());
if (fromRecord == null) throw new RuntimeException("habit not in database"); if (fromRecord == null)
if (toRecord == null) throw new RuntimeException("habit not in database"); throw new RuntimeException("habit not in database");
if (toRecord == null)
throw new RuntimeException("habit not in database");
Integer fromPos = fromRecord.position; Integer fromPos = fromRecord.position;
Integer toPos = toRecord.position; Integer toPos = toRecord.position;
Log.d("SQLiteHabitList", String.format("reorder: %d %d", fromPos, toPos)); Log.d("SQLiteHabitList",
String.format("reorder: %d %d", fromPos, toPos));
if (toPos < fromPos) if (toPos < fromPos)
{ {

@ -25,7 +25,6 @@ import com.activeandroid.*;
import com.activeandroid.annotation.*; import com.activeandroid.annotation.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.models.sqlite.*;
/** /**
* The SQLite database record corresponding to a {@link Checkmark}. * The SQLite database record corresponding to a {@link Checkmark}.
@ -63,8 +62,6 @@ public class CheckmarkRecord extends Model implements SQLiteRecord
public Checkmark toCheckmark() public Checkmark toCheckmark()
{ {
SQLiteHabitList habitList = SQLiteHabitList.getInstance();
Habit h = habitList.getById(habit.getId());
return new Checkmark(timestamp, value); return new Checkmark(timestamp, value);
} }
} }

@ -25,7 +25,6 @@ import com.activeandroid.*;
import com.activeandroid.annotation.*; import com.activeandroid.annotation.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.models.sqlite.*;
/** /**
* The SQLite database record corresponding to a {@link Repetition}. * The SQLite database record corresponding to a {@link Repetition}.
@ -57,8 +56,6 @@ public class RepetitionRecord extends Model implements SQLiteRecord
public Repetition toRepetition() public Repetition toRepetition()
{ {
SQLiteHabitList habitList = SQLiteHabitList.getInstance();
Habit h = habitList.getById(habit.getId());
return new Repetition(timestamp); return new Repetition(timestamp);
} }
} }

@ -25,7 +25,6 @@ import com.activeandroid.*;
import com.activeandroid.annotation.*; import com.activeandroid.annotation.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.models.sqlite.*;
/** /**
* The SQLite database record corresponding to a Score. * The SQLite database record corresponding to a Score.
@ -63,8 +62,6 @@ public class ScoreRecord extends Model implements SQLiteRecord
*/ */
public Score toScore() public Score toScore()
{ {
SQLiteHabitList habitList = SQLiteHabitList.getInstance();
Habit h = habitList.getById(habit.getId());
return new Score(timestamp, score); return new Score(timestamp, score);
} }
} }

@ -25,7 +25,6 @@ import com.activeandroid.*;
import com.activeandroid.annotation.*; import com.activeandroid.annotation.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.models.*;
import org.isoron.uhabits.models.sqlite.*;
import java.lang.reflect.*; import java.lang.reflect.*;
@ -86,8 +85,6 @@ public class StreakRecord extends Model implements SQLiteRecord
public Streak toStreak() public Streak toStreak()
{ {
SQLiteHabitList habitList = SQLiteHabitList.getInstance();
Habit h = habitList.getById(habit.getId());
return new Streak(start, end); return new Streak(start, end);
} }
} }

@ -21,11 +21,13 @@ package org.isoron.uhabits.tasks;
import android.support.annotation.*; import android.support.annotation.*;
import com.google.auto.factory.*;
import org.isoron.uhabits.io.*; import org.isoron.uhabits.io.*;
import org.isoron.uhabits.models.*;
import java.io.*; import java.io.*;
@AutoFactory
public class ImportDataTask implements Task public class ImportDataTask implements Task
{ {
public static final int FAILED = 3; public static final int FAILED = 3;
@ -39,18 +41,17 @@ public class ImportDataTask implements Task
@NonNull @NonNull
private final File file; private final File file;
@NonNull private GenericImporter importer;
private final Listener listener;
@NonNull @NonNull
private final HabitList habits; private final Listener listener;
public ImportDataTask(@NonNull HabitList habits, public ImportDataTask(@Provided @NonNull GenericImporter importer,
@NonNull File file, @NonNull File file,
@NonNull Listener listener) @NonNull Listener listener)
{ {
this.importer = importer;
this.listener = listener; this.listener = listener;
this.habits = habits;
this.file = file; this.file = file;
} }
@ -59,7 +60,6 @@ public class ImportDataTask implements Task
{ {
try try
{ {
GenericImporter importer = new GenericImporter(habits);
if (importer.canHandle(file)) if (importer.canHandle(file))
{ {
importer.importHabitsFromFile(file); importer.importHabitsFromFile(file);

@ -87,7 +87,7 @@ public class ListHabitsScreenTest extends BaseUnitTest
controller = mock(ListHabitsController.class); controller = mock(ListHabitsController.class);
screen.setController(controller); screen.setController(controller);
habit = new Habit(); habit = fixtures.createEmptyHabit();
intent = mock(Intent.class); intent = mock(Intent.class);
} }

@ -40,9 +40,10 @@ public class CreateHabitCommandTest extends BaseUnitTest
{ {
super.setUp(); super.setUp();
model = new Habit(); model = fixtures.createEmptyHabit();
model.setName("New habit"); model.setName("New habit");
command = new CreateHabitCommand(habitList, model);
command = new CreateHabitCommand(modelFactory, habitList, model);
fixtures.purgeHabits(); fixtures.purgeHabits();
} }

@ -45,7 +45,7 @@ public class EditHabitCommandTest extends BaseUnitTest
habit.setName("original"); habit.setName("original");
habit.setFrequency(Frequency.DAILY); habit.setFrequency(Frequency.DAILY);
modified = new Habit(); modified = fixtures.createEmptyHabit();
modified.copyFrom(habit); modified.copyFrom(habit);
modified.setName("modified"); modified.setName("modified");
} }
@ -53,7 +53,8 @@ public class EditHabitCommandTest extends BaseUnitTest
@Test @Test
public void testExecuteUndoRedo() public void testExecuteUndoRedo()
{ {
command = new EditHabitCommand(habitList, habit, modified); command =
new EditHabitCommand(modelFactory, habitList, habit, modified);
int originalScore = habit.getScores().getTodayValue(); int originalScore = habit.getScores().getTodayValue();
assertThat(habit.getName(), equalTo("original")); assertThat(habit.getName(), equalTo("original"));
@ -75,7 +76,8 @@ public class EditHabitCommandTest extends BaseUnitTest
public void testExecuteUndoRedo_withModifiedInterval() public void testExecuteUndoRedo_withModifiedInterval()
{ {
modified.setFrequency(Frequency.TWO_TIMES_PER_WEEK); modified.setFrequency(Frequency.TWO_TIMES_PER_WEEK);
command = new EditHabitCommand(habitList, habit, modified); command =
new EditHabitCommand(modelFactory, habitList, habit, modified);
int originalScore = habit.getScores().getTodayValue(); int originalScore = habit.getScores().getTodayValue();
assertThat(habit.getName(), equalTo("original")); assertThat(habit.getName(), equalTo("original"));

@ -34,8 +34,6 @@ import static org.hamcrest.core.IsEqual.equalTo;
@SuppressWarnings("JavaDoc") @SuppressWarnings("JavaDoc")
public class HabitListTest extends BaseUnitTest public class HabitListTest extends BaseUnitTest
{ {
private HabitList allHabits;
private ArrayList<Habit> habitsArray; private ArrayList<Habit> habitsArray;
private HabitList activeHabits; private HabitList activeHabits;
@ -46,16 +44,15 @@ public class HabitListTest extends BaseUnitTest
public void setUp() public void setUp()
{ {
super.setUp(); super.setUp();
fixtures.purgeHabits();
allHabits = modelFactory.buildHabitList();
habitsArray = new ArrayList<>(); habitsArray = new ArrayList<>();
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
Habit habit = new Habit(); Habit habit = fixtures.createEmptyHabit();
habit.setId((long) i); habit.setId((long) i);
habitsArray.add(habit); habitsArray.add(habit);
allHabits.add(habit);
if (i % 3 == 0) if (i % 3 == 0)
habit.setReminder(new Reminder(8, 30, WeekdayList.EVERY_DAY)); habit.setReminder(new Reminder(8, 30, WeekdayList.EVERY_DAY));
@ -66,9 +63,9 @@ public class HabitListTest extends BaseUnitTest
habitsArray.get(4).setArchived(true); habitsArray.get(4).setArchived(true);
habitsArray.get(7).setArchived(true); habitsArray.get(7).setArchived(true);
activeHabits = allHabits.getFiltered( activeHabits = habitList.getFiltered(new HabitMatcherBuilder().build());
new HabitMatcherBuilder().build());
reminderHabits = allHabits.getFiltered(new HabitMatcherBuilder() reminderHabits = habitList.getFiltered(new HabitMatcherBuilder()
.setArchivedAllowed(true) .setArchivedAllowed(true)
.setReminderRequired(true) .setReminderRequired(true)
.build()); .build());
@ -77,7 +74,7 @@ public class HabitListTest extends BaseUnitTest
@Test @Test
public void testSize() public void testSize()
{ {
assertThat(allHabits.size(), equalTo(10)); assertThat(habitList.size(), equalTo(10));
} }
@Test @Test
@ -89,9 +86,9 @@ public class HabitListTest extends BaseUnitTest
@Test @Test
public void test_getByPosition() public void test_getByPosition()
{ {
assertThat(allHabits.getByPosition(0), equalTo(habitsArray.get(0))); assertThat(habitList.getByPosition(0), equalTo(habitsArray.get(0)));
assertThat(allHabits.getByPosition(3), equalTo(habitsArray.get(3))); assertThat(habitList.getByPosition(3), equalTo(habitsArray.get(3)));
assertThat(allHabits.getByPosition(9), equalTo(habitsArray.get(9))); assertThat(habitList.getByPosition(9), equalTo(habitsArray.get(9)));
assertThat(activeHabits.getByPosition(0), equalTo(habitsArray.get(2))); assertThat(activeHabits.getByPosition(0), equalTo(habitsArray.get(2)));
} }
@ -107,14 +104,14 @@ public class HabitListTest extends BaseUnitTest
@Test @Test
public void test_get_withInvalidId() public void test_get_withInvalidId()
{ {
assertThat(allHabits.getById(100L), is(nullValue())); assertThat(habitList.getById(100L), is(nullValue()));
} }
@Test @Test
public void test_get_withValidId() public void test_get_withValidId()
{ {
Habit habit1 = habitsArray.get(0); Habit habit1 = habitsArray.get(0);
Habit habit2 = allHabits.getById(habit1.getId()); Habit habit2 = habitList.getById(habit1.getId());
assertThat(habit1, equalTo(habit2)); assertThat(habit1, equalTo(habit2));
} }
@ -137,17 +134,17 @@ public class HabitListTest extends BaseUnitTest
int from = operations[i][0]; int from = operations[i][0];
int to = operations[i][1]; int to = operations[i][1];
Habit fromHabit = allHabits.getByPosition(from); Habit fromHabit = habitList.getByPosition(from);
Habit toHabit = allHabits.getByPosition(to); Habit toHabit = habitList.getByPosition(to);
allHabits.reorder(fromHabit, toHabit); habitList.reorder(fromHabit, toHabit);
int actualPositions[] = new int[10]; int actualPositions[] = new int[10];
for (int j = 0; j < 10; j++) for (int j = 0; j < 10; j++)
{ {
Habit h = allHabits.getById(j); Habit h = habitList.getById(j);
if (h == null) fail(); if (h == null) fail();
actualPositions[j] = allHabits.indexOf(h); actualPositions[j] = habitList.indexOf(h);
} }
assertThat(actualPositions, equalTo(expectedPosition[i])); assertThat(actualPositions, equalTo(expectedPosition[i]));
@ -159,13 +156,13 @@ public class HabitListTest extends BaseUnitTest
{ {
HabitList list = modelFactory.buildHabitList(); HabitList list = modelFactory.buildHabitList();
Habit h1 = new Habit(); Habit h1 = fixtures.createEmptyHabit();
h1.setName("Meditate"); h1.setName("Meditate");
h1.setDescription("Did you meditate this morning?"); h1.setDescription("Did you meditate this morning?");
h1.setFrequency(Frequency.DAILY); h1.setFrequency(Frequency.DAILY);
h1.setColor(3); h1.setColor(3);
Habit h2 = new Habit(); Habit h2 = fixtures.createEmptyHabit();
h2.setName("Wake up early"); h2.setName("Wake up early");
h2.setDescription("Did you wake up before 6am?"); h2.setDescription("Did you wake up before 6am?");
h2.setFrequency(new Frequency(2, 3)); h2.setFrequency(new Frequency(2, 3));

@ -20,22 +20,24 @@
package org.isoron.uhabits.models; package org.isoron.uhabits.models;
import org.isoron.uhabits.*; import org.isoron.uhabits.*;
import org.junit.Test; import org.junit.*;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.*;
import static org.junit.Assert.assertThat;
public class HabitTest extends BaseUnitTest public class HabitTest extends BaseUnitTest
{ {
@Override
public void setUp()
{
super.setUp();
}
@Test @Test
public void testConstructor_default() public void testConstructor_default()
{ {
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
assertFalse(habit.isArchived()); assertFalse(habit.isArchived());
assertThat(habit.hasReminder(), is(false)); assertThat(habit.hasReminder(), is(false));
@ -48,13 +50,13 @@ public class HabitTest extends BaseUnitTest
@Test @Test
public void test_copyAttributes() public void test_copyAttributes()
{ {
Habit model = new Habit(); Habit model = modelFactory.buildHabit();
model.setArchived(true); model.setArchived(true);
model.setColor(0); model.setColor(0);
model.setFrequency(new Frequency(10, 20)); model.setFrequency(new Frequency(10, 20));
model.setReminder(new Reminder(8, 30, new WeekdayList(1))); model.setReminder(new Reminder(8, 30, new WeekdayList(1)));
Habit habit = new Habit(); Habit habit = modelFactory.buildHabit();
habit.copyFrom(model); habit.copyFrom(model);
assertThat(habit.isArchived(), is(model.isArchived())); assertThat(habit.isArchived(), is(model.isArchived()));
assertThat(habit.getColor(), is(model.getColor())); assertThat(habit.getColor(), is(model.getColor()));
@ -62,34 +64,11 @@ public class HabitTest extends BaseUnitTest
assertThat(habit.getReminder(), equalTo(model.getReminder())); assertThat(habit.getReminder(), equalTo(model.getReminder()));
} }
// @Test
// public void test_rebuildOrder()
// {
// List<Long> ids = new LinkedList<>();
// int originalPositions[] = { 0, 1, 1, 4, 6, 8, 10, 10, 13};
//
// for (int p : originalPositions)
// {
// Habit h = new Habit();
// habitList.insert(h);
// ids.add(h.getId());
// }
//
// ((SQLiteHabitList) habitList).rebuildOrder();
//
// for (int i = 0; i < originalPositions.length; i++)
// {
// Habit h = habitList.get(ids.get(i));
// if(h == null) fail();
// assertThat(habitList.indexOf(h), is(i));
// }
// }
@Test @Test
public void test_hasReminder_clearReminder() public void test_hasReminder_clearReminder()
{ {
Habit h = new Habit(); Habit h = modelFactory.buildHabit();
assertThat(h.hasReminder(), is(false)); assertThat(h.hasReminder(), is(false));
h.setReminder(new Reminder(8, 30, WeekdayList.EVERY_DAY)); h.setReminder(new Reminder(8, 30, WeekdayList.EVERY_DAY));

@ -19,27 +19,18 @@
package org.isoron.uhabits.models; package org.isoron.uhabits.models;
import android.support.annotation.NonNull; import android.support.annotation.*;
import org.isoron.uhabits.BaseUnitTest; import org.isoron.uhabits.*;
import org.isoron.uhabits.models.*; import org.isoron.uhabits.utils.*;
import org.isoron.uhabits.utils.DateUtils; import org.junit.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays; import java.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Random;
import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsEqual.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.*;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
public class RepetitionListTest extends BaseUnitTest public class RepetitionListTest extends BaseUnitTest
{ {
@ -61,7 +52,7 @@ public class RepetitionListTest extends BaseUnitTest
public void setUp() public void setUp()
{ {
super.setUp(); super.setUp();
habit = new Habit(); habit = fixtures.createEmptyHabit();
reps = habit.getRepetitions(); reps = habit.getRepetitions();
today = DateUtils.getStartOfToday(); today = DateUtils.getStartOfToday();
@ -105,7 +96,7 @@ public class RepetitionListTest extends BaseUnitTest
@Test @Test
public void test_getWeekDayFrequency() public void test_getWeekDayFrequency()
{ {
habit = new Habit(); habit = fixtures.createEmptyHabit();
reps = habit.getRepetitions(); reps = habit.getRepetitions();
Random random = new Random(); Random random = new Random();

Loading…
Cancel
Save