diff --git a/sample/build.gradle b/sample/build.gradle index 0bb25da..73a54b8 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -58,6 +58,8 @@ dependencies { implementation 'com.google.code.gson:gson:2.8.5' testImplementation 'junit:junit:4.12' + testImplementation 'org.mockito:mockito-core:2.7.22' + androidTestImplementation 'org.mockito:mockito-android:2.7.22' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' diff --git a/sample/src/androidTest/java/org/aerogear/graphqlandroid/ExampleInstrumentedTest.kt b/sample/src/androidTest/java/org/aerogear/graphqlandroid/InstrumentedTest.kt similarity index 55% rename from sample/src/androidTest/java/org/aerogear/graphqlandroid/ExampleInstrumentedTest.kt rename to sample/src/androidTest/java/org/aerogear/graphqlandroid/InstrumentedTest.kt index f48c14d..12511ea 100644 --- a/sample/src/androidTest/java/org/aerogear/graphqlandroid/ExampleInstrumentedTest.kt +++ b/sample/src/androidTest/java/org/aerogear/graphqlandroid/InstrumentedTest.kt @@ -2,23 +2,30 @@ package org.aerogear.graphqlandroid import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 +import org.aerogear.offix.getDao import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* +import org.junit.runners.JUnit4 /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ -@RunWith(AndroidJUnit4::class) -class ExampleInstrumentedTest { +@RunWith(JUnit4::class) +class InstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() + val args = InstrumentationRegistry.getArguments() assertEquals("com.lavanya.graphqlandroid", appContext.packageName) + assertEquals(0.1010001, args.getDouble("0.1010001")) + assertEquals(true, "test".contains("s")) + assertEquals("TasksApp", appContext.resources.getString(R.string.app_name)) //TODO: change it if you ever change the app name + assertEquals(0, getDao()?.getAllMutations()?.size); } } diff --git a/sample/src/main/java/org/aerogear/graphqlandroid/InputValidator.kt b/sample/src/main/java/org/aerogear/graphqlandroid/InputValidator.kt new file mode 100644 index 0000000..d36bac6 --- /dev/null +++ b/sample/src/main/java/org/aerogear/graphqlandroid/InputValidator.kt @@ -0,0 +1,33 @@ +package org.aerogear.graphqlandroid + +import java.util.regex.Pattern + +object InputValidator{ + val EMAIL_PATTERN = Pattern.compile( + "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + + "\\@" + + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + + "(" + + "\\." + + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + + ")+" + ) + fun taskValidation(id: String, title: String, description: String): Boolean{ + return (description.length <= 360 + && id.length!=0 + && title.length<100) + } + fun userValidation(idUser: String, + taskId: String, + title: String, + firstName: String, + lastName: String, + email: String): Boolean{ + return (firstName.length<20 + && lastName.length<20 + && EMAIL_PATTERN.matcher(email).matches() + && idUser.length!=0 + && taskId.length!=0 + && title.length<100) + } +} \ No newline at end of file diff --git a/sample/src/main/java/org/aerogear/graphqlandroid/activities/MainActivity.kt b/sample/src/main/java/org/aerogear/graphqlandroid/activities/MainActivity.kt index 3f8acb1..62f3d0c 100644 --- a/sample/src/main/java/org/aerogear/graphqlandroid/activities/MainActivity.kt +++ b/sample/src/main/java/org/aerogear/graphqlandroid/activities/MainActivity.kt @@ -8,37 +8,32 @@ import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater -import android.widget.Toast import com.apollographql.apollo.ApolloCall -import com.apollographql.apollo.ApolloQueryWatcher import com.apollographql.apollo.api.Response import com.apollographql.apollo.exception.ApolloException import com.apollographql.apollo.fetcher.ApolloResponseFetchers -import com.apollographql.apollo.rx2.Rx2Apollo -import io.reactivex.android.schedulers.AndroidSchedulers -import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers -import io.reactivex.subscribers.DisposableSubscriber import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.alertfrag_create_tasks.view.* -import org.aerogear.graphqlandroid.* +import org.aerogear.graphqlandroid.FindAllTasksQuery +import org.aerogear.graphqlandroid.R +import org.aerogear.graphqlandroid.Utils + +import org.aerogear.graphqlandroid.managers.MutationManager.createTask; +import org.aerogear.graphqlandroid.managers.SubscriptionManager.subscriptionNewTask +import org.aerogear.graphqlandroid.managers.SubscriptionManager.subscriptionNewUser +import org.aerogear.graphqlandroid.managers.SubscriptionManager.subscriptionUpdateTask +import org.aerogear.graphqlandroid.managers.SubscriptionManager.subscriptionUpdateUser import org.aerogear.graphqlandroid.adapter.TaskAdapter import org.aerogear.graphqlandroid.model.UserOutput -import org.aerogear.graphqlandroid.type.TaskInput -import org.aerogear.graphqlandroid.type.UserInput import org.aerogear.offix.Offline class MainActivity : AppCompatActivity() { - var tasksList = arrayListOf() private val TAG = javaClass.simpleName val taskAdapter by lazy { TaskAdapter(tasksList, this) } - private val disposables = CompositeDisposable() - private var apolloQueryWatcher: ApolloQueryWatcher? = null - override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) @@ -46,15 +41,15 @@ class MainActivity : AppCompatActivity() { fabAdd.setOnClickListener { //Used for creating a new task val inflatedView = - LayoutInflater.from(this).inflate(R.layout.alertfrag_create_tasks, null, false) + LayoutInflater.from(this).inflate(R.layout.alertfrag_create_tasks, null, false) val ilTitleTask = inflatedView.ilTitleTask val etTitleTask = inflatedView.etTitleTask etTitleTask.addTextChangedListener(object :TextWatcher{ override fun beforeTextChanged( - s: CharSequence?, - start: Int, - count: Int, - after: Int + s: CharSequence?, + start: Int, + count: Int, + after: Int ) { } @@ -71,13 +66,13 @@ class MainActivity : AppCompatActivity() { }) val customAlert: AlertDialog = AlertDialog.Builder(this) - .setView(inflatedView) - .setTitle(R.string.new_task) - .setNegativeButton(android.R.string.no) { dialog, _ -> - dialog.dismiss() - } - .setPositiveButton(android.R.string.yes, null) - .create() + .setView(inflatedView) + .setTitle(R.string.new_task) + .setNegativeButton(android.R.string.no) { dialog, _ -> + dialog.dismiss() + } + .setPositiveButton(android.R.string.yes, null) + .create() customAlert.setOnShowListener { val positiveButton = customAlert.getButton(AlertDialog.BUTTON_POSITIVE) positiveButton.setOnClickListener { @@ -86,7 +81,7 @@ class MainActivity : AppCompatActivity() { ilTitleTask.error = resources.getString(R.string.task_title_error) } else { val desc = inflatedView.etDescTask.text.toString() - createTask(title, desc) + createTask(title, desc, this) customAlert.dismiss() } } @@ -109,7 +104,6 @@ class MainActivity : AppCompatActivity() { tasksList.clear() getTasks() } - private fun getTasks() { Log.e(TAG, " ----- getTasks") @@ -117,481 +111,64 @@ class MainActivity : AppCompatActivity() { FindAllTasksQuery.builder()?.build()?.let { Utils.getApolloClient(this)?.query(it) - ?.responseFetcher(ApolloResponseFetchers.NETWORK_FIRST) - ?.enqueue(object : ApolloCall.Callback() { - - override fun onFailure(e: ApolloException) { - e.printStackTrace() - Log.e(TAG, "getTasks ----$e ") - } - - override fun onResponse(response: Response) { - Log.e(TAG, "on Response getTasks : Data ${response.data()}") - val result = response.data()?.findAllTasks() - - result?.forEach { allTasks -> - val title = allTasks.title() - val desc = allTasks.description() - val id = allTasks.id() - var firstName = "" - var lastName = "" - var email = "" - var userId = "" - allTasks.assignedTo()?.let { query -> - firstName = query.firstName() - lastName = query.lastName() - email = query.email() - userId = query.id() - } ?: kotlin.run { - firstName = "" - lastName = "" - email = "" - userId = "" - } - val taskOutput = UserOutput( - title, - desc, - id.toInt(), - firstName, - lastName, - userId, - email - ) - runOnUiThread { - tasksList.add(taskOutput) - taskAdapter.notifyDataSetChanged() - } - } - } - }) - } - } - - fun updateTask(id: String, title: String, description: String) { - Log.e(TAG, "inside update title in MainActivity") - - /* - As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) - */ - val input = - TaskInput.builder().title(title).version(1).description(description).status("test") - .build() - - val mutation = UpdateTaskMutation.builder().id(id).input(input).build() - - Log.e(TAG, " updateTask ********: - $mutation") - - val mutationCall = Utils.getApolloClient(this)?.mutate( - mutation - )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) - - Log.e(TAG, " updateTask class name: - ${mutation.javaClass.simpleName}") - Log.e( - TAG, - " updateTask 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" - ) - Log.e(TAG, " updateTask 21: - ${mutationCall?.operation()?.queryDocument()}") - Log.e(TAG, " updateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") - Log.e(TAG, " updateTask 23: - ${mutationCall?.operation()?.name()}") - - val callback = object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") - e.printStackTrace() - } - - override fun onResponse(response: Response) { - val result = response.data()?.updateTask() - - //In case of conflicts data returned from the server id null. - result?.let { - Log.e(TAG, "onResponse-UpdateTask- $it") - } - } - } - mutationCall?.enqueue(callback) - if (Offline.isNetwork()) { - Toast.makeText(this@MainActivity, "Task with id $id is updated", Toast.LENGTH_LONG) - .show() - } else { - Toast.makeText( - this@MainActivity, - "Task with id $id is stored offline. Changes will be synced to the server when app comes online.", - Toast.LENGTH_LONG - ).show() - - } - } - - fun updateUser( - idUser: String, - taskId: String, - title: String, - firstName: String, - lastName: String, - email: String - ) { - Log.e(TAG, "inside updateUser in MainActivity") - - val input = - UserInput.builder().title(title).lastName(lastName).firstName(firstName).email(email) - .taskId(taskId) - .creationmetadataId(taskId).build() - - val mutation = UpdateUserMutation.builder().id(idUser).input(input).build() - - Log.e(TAG, " updateUser ********: - $mutation") - - val mutationCall = Utils.getApolloClient(this)?.mutate( - mutation - )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) - - Log.e(TAG, " updateUser class name: - ${mutation.javaClass.simpleName}") - Log.e( - TAG, - " updateUser 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" - ) - Log.e(TAG, " updateUser 21: - ${mutationCall?.operation()?.queryDocument()}") - Log.e(TAG, " updateUser 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") - Log.e(TAG, " updateUser 23: - ${mutationCall?.operation()?.name()}") - - val callback = object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") - e.printStackTrace() - } - - override fun onResponse(response: Response) { - val result = response.data()?.updateUser() - - //In case of conflicts data returned from the server id null. - result?.let { - Log.e(TAG, "onResponse-UpdateTask- $it") - } - } - } - mutationCall?.enqueue(callback) - if (Offline.isNetwork()) { - Toast.makeText( - this, - resources.getText(R.string.user_updated, idUser), - Toast.LENGTH_LONG - ).show() - } else { - Toast.makeText( - this, - resources.getText(R.string.user_updates_stored, idUser), - Toast.LENGTH_LONG - ).show() - } - - } - - private fun createTask(title: String, description: String) { - Log.e(TAG, "inside create title") - - /* - As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) - */ - val input = - TaskInput.builder().title(title).description(description).version(1).status("test") - .build() - - val mutation = CreateTaskMutation.builder().input(input).build() - - val mutationCall = Utils.getApolloClient(this)?.mutate( - mutation - )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) - - Log.e(TAG, " updateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") - - - val callback = object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") - e.printStackTrace() - } - - override fun onResponse(response: Response) { - val result = response.data()?.createTask() - - //In case of conflicts data returned from the server id null. - result?.let { - Log.e(TAG, "onResponse-UpdateTask- $it") - } - } - } - mutationCall?.enqueue(callback) - - if (Offline.isNetwork()) { - Toast.makeText(this, "Mutation with title $title is created", Toast.LENGTH_LONG).show() - } else { - Toast.makeText( - this, - "Create mutation with title $title is stored offline. Changes will be synced to the server when app comes online.", - Toast.LENGTH_LONG - ).show() - } - } - - fun createUser( - title: String, - firstName: String, - lastName: String, - email: String, - taskId: String - ) { - Log.e(TAG, "inside create user") - - val input = - UserInput.builder().taskId(taskId).email(email).firstName(firstName).lastName(lastName) - .title(title) - .creationmetadataId(taskId).build() + ?.responseFetcher(ApolloResponseFetchers.NETWORK_FIRST) + ?.enqueue(object : ApolloCall.Callback() { - val mutation = CreateUserMutation.builder().input(input).build() - - val mutationCall = Utils.getApolloClient(this)?.mutate( - mutation - )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) - - Log.e(TAG, " createUser 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") - val callback = object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") - e.printStackTrace() - } - - override fun onResponse(response: Response) { - val result = response.data()?.createUser() - - //In case of conflicts data returned from the server id null. - result?.let { - Log.e(TAG, "onResponse-UpdateTask- $it") - } - } - } - mutationCall?.enqueue(callback) - if (Offline.isNetwork()) { - Toast.makeText( - this, - "Task with id $taskId is assigned to $firstName $lastName", - Toast.LENGTH_LONG - ) - .show() - } else { - Toast.makeText( - this, - "Update in user where Task with id $taskId is assigned to $firstName $lastName is stored offline. Changes will be synced to the server when app comes online.", - Toast.LENGTH_LONG - ).show() - } - } - - fun checkAndUpdateTask(id: String, title: String, description: String) { - Log.e(TAG, "inside checkAndUpdateTask in MainActivity") - - /* - As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) - */ - - val mutation = - CheckAndUpdateTaskMutation.builder().version(1).id(id).title(title) - .description(description).status("test") - .build() - - Log.e(TAG, " checkAndUpdateTask ********: - $mutation") - - val mutationCall = Utils.getApolloClient(this)?.mutate( - mutation - )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) - - Log.e(TAG, " checkAndUpdateTask class name: - ${mutation.javaClass.simpleName}") - Log.e( - TAG, - " checkAndUpdateTask 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" - ) - Log.e(TAG, " checkAndUpdateTask 21: - ${mutationCall?.operation()?.queryDocument()}") - Log.e( - TAG, - " checkAndUpdateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}" - ) - Log.e(TAG, " checkAndUpdateTask 23: - ${mutationCall?.operation()?.name()}") - - val callback = object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") - e.printStackTrace() - } - - override fun onResponse(response: Response) { - val result = response.data()?.checkAndUpdateTask() - - //In case of conflicts data returned from the server id null. - result?.let { - Log.e(TAG, "onResponse-UpdateTask- $it") - } - } - } - mutationCall?.enqueue(callback) - if (Offline.isNetwork()) { - Toast.makeText( - this@MainActivity, - "Task with id $id is updated without any Conflict.", - Toast.LENGTH_LONG - ) - .show() - } else { - Toast.makeText( - this@MainActivity, - "Task with id $id is stored offline. Changes will be synced to the server when app comes online.", - Toast.LENGTH_LONG - ).show() - } - } - - private fun subscriptionNewTask() { - val subscription = NewTaskSubscription() - val subscriptionCall = Utils.getApolloClient(this) - ?.subscribe(subscription) - - disposables.add( - Rx2Apollo.from(subscriptionCall!!) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - object : DisposableSubscriber>() { - override fun onNext(response: Response) { - val res = response.data()?.newTask() - res?.let { - } - } - - override fun onError(e: Throwable) { - Log.e(TAG, e.message, e) - } - - override fun onComplete() { - Log.e(TAG, "Subscription new task added exhausted") + override fun onFailure(e: ApolloException) { + e.printStackTrace() + Log.e(TAG, "getTasks ----$e ") } - } - ) - ) - } - - private fun subscriptionUpdateTask() { - - val subscription = UpdatedTaskSubscription() - val subscriptionCall = Utils.getApolloClient(this) - ?.subscribe(subscription) - - disposables.add(Rx2Apollo.from(subscriptionCall!!) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - object : DisposableSubscriber>() { - override fun onNext(response: Response) { - val res = response.data()?.updatedTask() - res?.let { - Log.e( - TAG, - " inside subscriptionUpdateTask ${it.title()} mutated upon updating" - ) - } - } - - override fun onError(e: Throwable) { - Log.e(TAG, e.message, e) - } - override fun onComplete() { - Log.e(TAG, "subscriptionUpdateTask exhausted") - } - } - ) - ) - } - - private fun subscriptionNewUser() { - val subscription = NewUserSubscription() - val subscriptionCall = Utils.getApolloClient(this) - ?.subscribe(subscription) - - disposables.add( - Rx2Apollo.from(subscriptionCall!!) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - object : DisposableSubscriber>() { - override fun onNext(response: Response) { - val res = response.data()?.newUser() - res?.let { - Log.e( - TAG, - " inside subscriptionNewUser ${it.title()} mutated upon new title" + override fun onResponse(response: Response) { + Log.e(TAG, "on Response getTasks : Data ${response.data()}") + val result = response.data()?.findAllTasks() + + result?.forEach { allTasks -> + val title = allTasks.title() + val desc = allTasks.description() + val id = allTasks.id() + var firstName = "" + var lastName = "" + var email = "" + var userId = "" + allTasks.assignedTo()?.let { query -> + firstName = query.firstName() + lastName = query.lastName() + email = query.email() + userId = query.id() + } ?: kotlin.run { + firstName = "" + lastName = "" + email = "" + userId = "" + } + val taskOutput = UserOutput( + title, + desc, + id.toInt(), + firstName, + lastName, + userId, + email ) + runOnUiThread { + tasksList.add(taskOutput) + taskAdapter.notifyDataSetChanged() + } } } - - override fun onError(e: Throwable) { - Log.e(TAG, e.message, e) - } - - override fun onComplete() { - Log.e(TAG, "Subscription new user added exhausted") - } - } - ) - ) - } - - private fun subscriptionUpdateUser() { - - val subscription = UpdatedUserSubscription() - val subscriptionCall = Utils.getApolloClient(this) - ?.subscribe(subscription) - - disposables.add(Rx2Apollo.from(subscriptionCall!!) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - object : DisposableSubscriber>() { - override fun onNext(response: Response) { - - val res = response.data()?.updatedUser() - res?.let { - Log.e( - TAG, - " inside subscriptionUpdateUser ${it.title()} mutated upon updating" - ) - } - } - - override fun onError(e: Throwable) { - Log.e(TAG, e.message, e) - } - - override fun onComplete() { - Log.e(TAG, "subscriptionUpdateUser exhausted") - } - } - ) - ) + }) + } } override fun onStart() { if (Offline.isNetwork()) { - subscriptionNewTask() - subscriptionNewUser() - subscriptionUpdateTask() - subscriptionUpdateUser() + subscriptionNewTask(this) + subscriptionNewUser(this) + subscriptionUpdateTask(this) + subscriptionUpdateUser(this) } super.onStart() } - - override fun onDestroy() { - apolloQueryWatcher?.cancel() - disposables.dispose() - super.onDestroy() - } } diff --git a/sample/src/main/java/org/aerogear/graphqlandroid/adapter/TaskAdapter.kt b/sample/src/main/java/org/aerogear/graphqlandroid/adapter/TaskAdapter.kt index 4a353be..b9bfe90 100644 --- a/sample/src/main/java/org/aerogear/graphqlandroid/adapter/TaskAdapter.kt +++ b/sample/src/main/java/org/aerogear/graphqlandroid/adapter/TaskAdapter.kt @@ -14,6 +14,10 @@ import kotlinx.android.synthetic.main.alert_update_user.view.* import kotlinx.android.synthetic.main.alertfrag_create_user.view.* import kotlinx.android.synthetic.main.alertfrag_create_user.view.etTitleUser import kotlinx.android.synthetic.main.item_row_tasks.view.* +import org.aerogear.graphqlandroid.managers.MutationManager.checkAndUpdateTask +import org.aerogear.graphqlandroid.managers.MutationManager.createUser +import org.aerogear.graphqlandroid.managers.MutationManager.updateTask +import org.aerogear.graphqlandroid.managers.MutationManager.updateUser import org.aerogear.graphqlandroid.R import org.aerogear.graphqlandroid.activities.MainActivity import org.aerogear.graphqlandroid.model.UserOutput @@ -71,10 +75,11 @@ class TaskAdapter(private val notes: List, private val context: Cont val id = inflatedView.etId.text.toString() val titleEt = inflatedView.etTitle.text.toString() val description = inflatedView.etDesc.text.toString() - if (context is MainActivity) this.context.updateTask( + if (context is MainActivity) updateTask( id, titleEt, - description + description, + context ) dialog.dismiss() } @@ -100,10 +105,11 @@ class TaskAdapter(private val notes: List, private val context: Cont val id = inflatedView.etId.text.toString() val titleEt = inflatedView.etTitle.text.toString() val description = inflatedView.etDesc.text.toString() - if (context is MainActivity) this.context.checkAndUpdateTask( + if (context is MainActivity) checkAndUpdateTask( id, titleEt, - description + description, + context ) dialog.dismiss() Toast.makeText( @@ -137,12 +143,13 @@ class TaskAdapter(private val notes: List, private val context: Cont val firstName = inflatedView.etFirstName.text.toString() val lastName = inflatedView.etLastName.text.toString() val email = inflatedView.etEmail.text.toString() - if (context is MainActivity) this.context.createUser( + if (context is MainActivity) createUser( title, firstName, lastName, email, - idTask + idTask, + context ) buttonView.isChecked = true dialog.dismiss() @@ -181,13 +188,14 @@ class TaskAdapter(private val notes: List, private val context: Cont val firstName = inflatedView.etFname.text.toString() val lastName = inflatedView.etLname.text.toString() val email = inflatedView.etLEmailUSer.text.toString() - if (context is MainActivity) this.context.updateUser( + if (context is MainActivity) updateUser( userId, taskId, title, firstName, lastName, - email + email, + context ) dialog.dismiss() } diff --git a/sample/src/main/java/org/aerogear/graphqlandroid/managers/MutationManager.kt b/sample/src/main/java/org/aerogear/graphqlandroid/managers/MutationManager.kt new file mode 100644 index 0000000..c402628 --- /dev/null +++ b/sample/src/main/java/org/aerogear/graphqlandroid/managers/MutationManager.kt @@ -0,0 +1,321 @@ +package org.aerogear.graphqlandroid.managers + +import android.content.Context +import android.util.Log +import android.widget.Toast +import com.apollographql.apollo.ApolloCall +import com.apollographql.apollo.ApolloQueryWatcher +import com.apollographql.apollo.api.Response +import com.apollographql.apollo.exception.ApolloException +import org.aerogear.graphqlandroid.* +import org.aerogear.graphqlandroid.InputValidator.taskValidation +import org.aerogear.graphqlandroid.InputValidator.userValidation +import org.aerogear.graphqlandroid.type.TaskInput +import org.aerogear.graphqlandroid.type.UserInput +import org.aerogear.offix.Offline + +object MutationManager { + private val TAG = "MutationManager" + private var apolloQueryWatcher: ApolloQueryWatcher? = null + + fun updateTask(id: String, title: String, description: String, context: Context) { + Log.e(TAG, "inside update title in MainActivity") + + /* + As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) + */ + if(taskValidation(id, title, description)) { + val input = + TaskInput.builder().title(title).version(1).description(description).status("test") + .build() + + val mutation = UpdateTaskMutation.builder().id(id).input(input).build() + + + Log.e(TAG, " updateTask ********: - $mutation") + + val mutationCall = Utils.getApolloClient(context)?.mutate( + mutation + )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) + + Log.e(TAG, " updateTask class name: - ${mutation.javaClass.simpleName}") + Log.e( + TAG, + " updateTask 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" + ) + Log.e(TAG, " updateTask 21: - ${mutationCall?.operation()?.queryDocument()}") + Log.e(TAG, " updateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") + Log.e(TAG, " updateTask 23: - ${mutationCall?.operation()?.name()}") + + val callback = object : ApolloCall.Callback() { + override fun onFailure(e: ApolloException) { + Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") + e.printStackTrace() + } + + override fun onResponse(response: Response) { + val result = response.data()?.updateTask() + + //In case of conflicts data returned from the server id null. + result?.let { + Log.e(TAG, "onResponse-UpdateTask- $it") + } + } + } + mutationCall?.enqueue(callback) + if (Offline.isNetwork()) { + Toast.makeText(context, "Task with id $id is updated", Toast.LENGTH_LONG) + .show() + } else { + Toast.makeText( + context, + "Task with id $id is stored offline. Changes will be synced to the server when app comes online.", + Toast.LENGTH_LONG + ).show() + + } + } else { + Toast.makeText(context, "Task input not valid", Toast.LENGTH_SHORT) + } + } + + fun updateUser( + idUser: String, + taskId: String, + title: String, + firstName: String, + lastName: String, + email: String, + context: Context + ) { + Log.e(TAG, "inside updateUser in MainActivity") + if(userValidation(idUser, taskId, title, firstName, lastName, email)){ + val input = + UserInput.builder().title(title).lastName(lastName).firstName(firstName).email(email) + .taskId(taskId) + .creationmetadataId(taskId).build() + + val mutation = UpdateUserMutation.builder().id(idUser).input(input).build() + + Log.e(TAG, " updateUser ********: - $mutation") + + val mutationCall = Utils.getApolloClient(context)?.mutate( + mutation + )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) + + Log.e(TAG, " updateUser class name: - ${mutation.javaClass.simpleName}") + Log.e( + TAG, + " updateUser 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" + ) + Log.e(TAG, " updateUser 21: - ${mutationCall?.operation()?.queryDocument()}") + Log.e(TAG, " updateUser 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") + Log.e(TAG, " updateUser 23: - ${mutationCall?.operation()?.name()}") + + val callback = object : ApolloCall.Callback() { + override fun onFailure(e: ApolloException) { + Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") + e.printStackTrace() + } + + override fun onResponse(response: Response) { + val result = response.data()?.updateUser() + + //In case of conflicts data returned from the server id null. + result?.let { + Log.e(TAG, "onResponse-UpdateTask- $it") + } + } + } + mutationCall?.enqueue(callback) + if (Offline.isNetwork()) { + Toast.makeText( + context, + context.resources.getText(R.string.user_updated, idUser), + Toast.LENGTH_LONG + ).show() + } else { + Toast.makeText( + context, + context.resources.getText(R.string.user_updates_stored, idUser), + Toast.LENGTH_LONG + ).show() + } + } else { + Toast.makeText(context, "User input not valid", Toast.LENGTH_SHORT) + } + + } + + fun createTask(title: String, description: String, context: Context) { + Log.e(TAG, "inside create title") + if(taskValidation("0", title, description)){ + /* + As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) + */ + val input = + TaskInput.builder().title(title).description(description).version(1).status("test") + .build() + + val mutation = CreateTaskMutation.builder().input(input).build() + + val mutationCall = Utils.getApolloClient(context)?.mutate( + mutation + )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) + + Log.e(TAG, " updateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") + + + val callback = object : ApolloCall.Callback() { + override fun onFailure(e: ApolloException) { + Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") + e.printStackTrace() + } + + override fun onResponse(response: Response) { + val result = response.data()?.createTask() + + //In case of conflicts data returned from the server id null. + result?.let { + Log.e(TAG, "onResponse-UpdateTask- $it") + } + } + } + mutationCall?.enqueue(callback) + + if (Offline.isNetwork()) { + Toast.makeText(context, "Mutation with title $title is created", Toast.LENGTH_LONG).show() + } else { + Toast.makeText( + context, + "Create mutation with title $title is stored offline. Changes will be synced to the server when app comes online.", + Toast.LENGTH_LONG + ).show() + } + } else { + Toast.makeText(context, "Task input not valid", Toast.LENGTH_SHORT) + } + } + + fun createUser( + title: String, + firstName: String, + lastName: String, + email: String, + taskId: String, + context: Context + ) { + Log.e(TAG, "inside create user") + if(userValidation("0", taskId, title, firstName, lastName, email)){ + val input = + UserInput.builder().taskId(taskId).email(email).firstName(firstName).lastName(lastName) + .title(title) + .creationmetadataId(taskId).build() + + val mutation = CreateUserMutation.builder().input(input).build() + + val mutationCall = Utils.getApolloClient(context)?.mutate( + mutation + )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) + + Log.e(TAG, " createUser 22: - ${mutationCall?.operation()?.variables()?.valueMap()}") + val callback = object : ApolloCall.Callback() { + override fun onFailure(e: ApolloException) { + Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") + e.printStackTrace() + } + + override fun onResponse(response: Response) { + val result = response.data()?.createUser() + + //In case of conflicts data returned from the server id null. + result?.let { + Log.e(TAG, "onResponse-UpdateTask- $it") + } + } + } + mutationCall?.enqueue(callback) + if (Offline.isNetwork()) { + Toast.makeText( + context, + "Task with id $taskId is assigned to $firstName $lastName", + Toast.LENGTH_LONG + ) + .show() + } else { + Toast.makeText( + context, + "Update in user where Task with id $taskId is assigned to $firstName $lastName is stored offline. Changes will be synced to the server when app comes online.", + Toast.LENGTH_LONG + ).show() + } + } else { + Toast.makeText(context, "User input not valid", Toast.LENGTH_SHORT) + } + } + + fun checkAndUpdateTask(id: String, title: String, description: String, context: Context) { + Log.e(TAG, "inside checkAndUpdateTask in MainActivity") + + /* + As version is assumed to be auto incremented ( //TODO Have to make changes in sqlite db) + */ + if(taskValidation(id, title, description)){ + val mutation = + CheckAndUpdateTaskMutation.builder().version(1).id(id).title(title) + .description(description).status("test") + .build() + + Log.e(TAG, " checkAndUpdateTask ********: - $mutation") + + val mutationCall = Utils.getApolloClient(context)?.mutate( + mutation + )?.refetchQueries(apolloQueryWatcher?.operation()?.name()) + + Log.e(TAG, " checkAndUpdateTask class name: - ${mutation.javaClass.simpleName}") + Log.e( + TAG, + " checkAndUpdateTask 20: - ${mutationCall?.requestHeaders(com.apollographql.apollo.request.RequestHeaders.builder().build())}" + ) + Log.e(TAG, " checkAndUpdateTask 21: - ${mutationCall?.operation()?.queryDocument()}") + Log.e( + TAG, + " checkAndUpdateTask 22: - ${mutationCall?.operation()?.variables()?.valueMap()}" + ) + Log.e(TAG, " checkAndUpdateTask 23: - ${mutationCall?.operation()?.name()}") + + val callback = object : ApolloCall.Callback() { + override fun onFailure(e: ApolloException) { + Log.e("onFailure() updateTask", "${mutation.variables().valueMap()}") + e.printStackTrace() + } + + override fun onResponse(response: Response) { + val result = response.data()?.checkAndUpdateTask() + + //In case of conflicts data returned from the server id null. + result?.let { + Log.e(TAG, "onResponse-UpdateTask- $it") + } + } + } + mutationCall?.enqueue(callback) + if (Offline.isNetwork()) { + Toast.makeText( + context, + "Task with id $id is updated without any Conflict.", + Toast.LENGTH_LONG + ) + .show() + } else { + Toast.makeText( + context, + "Task with id $id is stored offline. Changes will be synced to the server when app comes online.", + Toast.LENGTH_LONG + ).show() + } + } else { + Toast.makeText(context, "Task input not valid", Toast.LENGTH_SHORT) + } + } +} \ No newline at end of file diff --git a/sample/src/main/java/org/aerogear/graphqlandroid/managers/SubscriptionManager.kt b/sample/src/main/java/org/aerogear/graphqlandroid/managers/SubscriptionManager.kt new file mode 100644 index 0000000..44c7682 --- /dev/null +++ b/sample/src/main/java/org/aerogear/graphqlandroid/managers/SubscriptionManager.kt @@ -0,0 +1,147 @@ +package org.aerogear.graphqlandroid.managers + +import android.content.Context +import android.util.Log +import com.apollographql.apollo.api.Response +import com.apollographql.apollo.rx2.Rx2Apollo +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import io.reactivex.subscribers.DisposableSubscriber +import org.aerogear.graphqlandroid.* + +object SubscriptionManager{ + private val disposables = CompositeDisposable() + private val TAG = "SubscriptionManager" + + public fun subscriptionNewTask(context: Context) { + val subscription = NewTaskSubscription() + val subscriptionCall = Utils.getApolloClient(context) + ?.subscribe(subscription) + + disposables.add( + Rx2Apollo.from(subscriptionCall!!) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith( + object : DisposableSubscriber>() { + override fun onNext(response: Response) { + val res = response.data()?.newTask() + res?.let { + } + } + + override fun onError(e: Throwable) { + Log.e(TAG, e.message, e) + } + + override fun onComplete() { + Log.e(TAG, "Subscription new task added exhausted") + } + } + ) + ) + } + + public fun subscriptionUpdateTask(context: Context) { + + val subscription = UpdatedTaskSubscription() + val subscriptionCall = Utils.getApolloClient(context) + ?.subscribe(subscription) + + disposables.add( + Rx2Apollo.from(subscriptionCall!!) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith( + object : DisposableSubscriber>() { + override fun onNext(response: Response) { + val res = response.data()?.updatedTask() + res?.let { + Log.e( + TAG, + " inside subscriptionUpdateTask ${it.title()} mutated upon updating" + ) + } + } + + override fun onError(e: Throwable) { + Log.e(TAG, e.message, e) + } + + override fun onComplete() { + Log.e(TAG, "subscriptionUpdateTask exhausted") + } + } + ) + ) + } + + public fun subscriptionNewUser(context: Context) { + val subscription = NewUserSubscription() + val subscriptionCall = Utils.getApolloClient(context) + ?.subscribe(subscription) + + disposables.add( + Rx2Apollo.from(subscriptionCall!!) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith( + object : DisposableSubscriber>() { + override fun onNext(response: Response) { + val res = response.data()?.newUser() + res?.let { + Log.e( + TAG, + " inside subscriptionNewUser ${it.title()} mutated upon new title" + ) + } + } + + override fun onError(e: Throwable) { + Log.e(TAG, e.message, e) + } + + override fun onComplete() { + Log.e(TAG, "Subscription new user added exhausted") + } + } + ) + ) + } + + public fun subscriptionUpdateUser(context: Context) { + + val subscription = UpdatedUserSubscription() + val subscriptionCall = Utils.getApolloClient(context) + ?.subscribe(subscription) + + disposables.add( + Rx2Apollo.from(subscriptionCall!!) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith( + object : DisposableSubscriber>() { + override fun onNext(response: Response) { + + val res = response.data()?.updatedUser() + res?.let { + Log.e( + TAG, + " inside subscriptionUpdateUser ${it.title()} mutated upon updating" + ) + } + } + + override fun onError(e: Throwable) { + Log.e(TAG, e.message, e) + } + + override fun onComplete() { + Log.e(TAG, "subscriptionUpdateUser exhausted") + } + } + ) + ) + } +} \ No newline at end of file diff --git a/sample/src/test/java/org/aerogear/graphqlandroid/ExampleUnitTest.kt b/sample/src/test/java/org/aerogear/graphqlandroid/ExampleUnitTest.kt deleted file mode 100644 index 12ff30b..0000000 --- a/sample/src/test/java/org/aerogear/graphqlandroid/ExampleUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package org.aerogear.graphqlandroid - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} diff --git a/sample/src/test/java/org/aerogear/graphqlandroid/UnitTest.kt b/sample/src/test/java/org/aerogear/graphqlandroid/UnitTest.kt new file mode 100644 index 0000000..462053a --- /dev/null +++ b/sample/src/test/java/org/aerogear/graphqlandroid/UnitTest.kt @@ -0,0 +1,43 @@ +package org.aerogear.graphqlandroid + +import org.aerogear.graphqlandroid.InputValidator.taskValidation +import org.aerogear.graphqlandroid.InputValidator.userValidation +import org.aerogear.offix.getDao +import org.junit.Test + +import org.junit.Assert.* +import org.junit.runner.RunWith +import org.mockito.junit.MockitoJUnitRunner + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(MockitoJUnitRunner::class) +class UnitTest { + @Test + fun isCorrect() { + assertEquals(4, 2 + 2) + assertEquals(null, getDao()?.getAllMutations()?.size) + assertEquals("http://10.0.2.2:4000/graphql", Utils.BASE_URL) + } + + @Test + fun taskValidator_ReturnsTrue() { + assertTrue(taskValidation("0", "title", "desc")) + } + @Test + fun taskValidator_ReturnsFalse() { + assertFalse(taskValidation("", "title", "desc")) + } + @Test + fun userValidator_ReturnsTrue() { + assertTrue(userValidation("0", "00", "title", "fn", "ln", "name@example.com")) + } + @Test + fun userValidator_ReturnsFalse() { + assertFalse(userValidation("0", "00", "title", "fn1", "ln2", "name@example..com")) + } + +}