Skip to content

Commit

Permalink
JSESSIONID cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
icrc-psousa committed Jun 12, 2024
1 parent 8342ffb commit e21843d
Show file tree
Hide file tree
Showing 7 changed files with 539 additions and 9 deletions.
412 changes: 411 additions & 1 deletion app/build.gradle.kts

Large diffs are not rendered by default.

Binary file added app/libs/engine-release.aar
Binary file not shown.
68 changes: 63 additions & 5 deletions app/src/main/java/org/openmrs/android/fhir/FhirApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,21 @@ import com.google.android.fhir.DatabaseErrorStrategy.RECREATE_AT_OPEN
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.FhirEngineConfiguration
import com.google.android.fhir.FhirEngineProvider
import com.google.android.fhir.NetworkConfiguration
import com.google.android.fhir.ServerConfiguration
import com.google.android.fhir.datacapture.DataCaptureConfig
import com.google.android.fhir.datacapture.XFhirQueryResolver
import com.google.android.fhir.search.search
import com.google.android.fhir.sync.remote.HttpLogger
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import timber.log.Timber
import java.io.IOException

class FhirApplication : Application(), DataCaptureConfig.Provider {
// Only initiate the FhirEngine when used for the first time, not when the app is created.
Expand All @@ -36,18 +45,70 @@ class FhirApplication : Application(), DataCaptureConfig.Provider {

private val dataStore by lazy { DemoDataStore(this) }

private lateinit var networkConfiguration: NetworkConfiguration

override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}

// Dummy request just to fetch JSESSIONID cookie
val url = "http://10.0.2.2:8080/openmrs/ws/rest/v1/session"
val json = """{"sessionLocation": "2d9378e3-b99f-42af-a109-f68395141bf3"}"""
val requestBody = RequestBody.create("application/json; charset=utf-8".toMediaType(), json)
val request = Request.Builder().url(url).get().build()
// Execute request
OkHttpClient().newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}

override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
networkConfiguration = NetworkConfiguration(cookie = response.headers.get("Set-Cookie").toString())

initFhirEngine()
}
}
})


// FhirEngineProvider.init(
// FhirEngineConfiguration(
// enableEncryptionIfSupported = false,
// RECREATE_AT_OPEN,
// ServerConfiguration(
// ServerConstants.BASE_URL,
// authenticator = LoginRepository.getInstance(applicationContext),
// networkConfiguration = networkConfiguration,
// httpLogger = HttpLogger(
// HttpLogger.Configuration(
// if (BuildConfig.DEBUG) HttpLogger.Level.BODY else HttpLogger.Level.BASIC,
// ),
// ) {
// Timber.tag("App-HttpLog").d(it)
// }
// )
// )
// )
dataCaptureConfig =
DataCaptureConfig().apply {
urlResolver = ReferenceUrlResolver(this@FhirApplication as Context)
xFhirQueryResolver = XFhirQueryResolver { it -> fhirEngine.search(it).map { it.resource } }
}
}

private fun initFhirEngine() {
FhirEngineProvider.init(
FhirEngineConfiguration(
enableEncryptionIfSupported = false,
RECREATE_AT_OPEN,
ServerConfiguration(
ServerConstants.BASE_URL,
authenticator = LoginRepository.getInstance(applicationContext),
networkConfiguration = networkConfiguration,
httpLogger = HttpLogger(
HttpLogger.Configuration(
if (BuildConfig.DEBUG) HttpLogger.Level.BODY else HttpLogger.Level.BASIC,
Expand All @@ -58,11 +119,6 @@ class FhirApplication : Application(), DataCaptureConfig.Provider {
)
)
)
dataCaptureConfig =
DataCaptureConfig().apply {
urlResolver = ReferenceUrlResolver(this@FhirApplication as Context)
xFhirQueryResolver = XFhirQueryResolver { it -> fhirEngine.search(it).map { it.resource } }
}
}

private fun constructFhirEngine(): FhirEngine {
Expand All @@ -73,6 +129,8 @@ class FhirApplication : Application(), DataCaptureConfig.Provider {
fun fhirEngine(context: Context) = (context.applicationContext as FhirApplication).fhirEngine

fun dataStore(context: Context) = (context.applicationContext as FhirApplication).dataStore

fun networkConfiguration(context: Context) = (context.applicationContext as FhirApplication).networkConfiguration
}

override fun getDataCaptureConfig(): DataCaptureConfig = dataCaptureConfig ?: DataCaptureConfig()
Expand Down
39 changes: 39 additions & 0 deletions app/src/main/java/org/openmrs/android/fhir/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,20 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import com.google.android.fhir.NetworkConfiguration
import com.google.android.fhir.sync.CurrentSyncJobStatus
import org.openmrs.android.fhir.databinding.ActivityMainBinding
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.openmrs.android.fhir.viewmodel.MainActivityViewModel
import timber.log.Timber
import java.io.IOException

const val MAX_RESOURCE_COUNT = 20

Expand All @@ -47,6 +56,36 @@ class MainActivity : AppCompatActivity() {
observeLastSyncTime()
observeSyncState()
viewModel.updateLastSyncTimestamp()

val networkConfiguration: NetworkConfiguration = FhirApplication.networkConfiguration(application.applicationContext)


// Set session location
val client = OkHttpClient()
val url = "http://10.0.2.2:8080/openmrs/ws/rest/v1/session"
val json = """{"sessionLocation": "2d9378e3-b99f-42af-a109-f68395141bf3"}"""
val requestBody = RequestBody.create("application/json; charset=utf-8".toMediaType(), json)
val request = Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + LoginRepository.getInstance(applicationContext).getAccessToken())
.addHeader("Cookie", networkConfiguration.cookie)
.post(requestBody)
.build()

client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}

override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body?.string())
}
}
})


}

override fun onBackPressed() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class FhirSyncWorker(appContext: Context, workerParams: WorkerParameters) :
}


override fun getUploadStrategy(): UploadStrategy = UploadStrategy.AllChangesSquashedBundlePut
override fun getUploadStrategy(): UploadStrategy = UploadStrategy.AllChangesIndividualResourcesPut

override fun getConflictResolver() = AcceptLocalConflictResolver

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ import java.util.*

class TimestampBasedDownloadWorkManagerImpl(private val dataStore: DemoDataStore) : DownloadWorkManager {
private val resourceTypeList = ResourceType.values().map { it.name }
private val urls = LinkedList(listOf("Patient?_sort=_lastUpdated"))
//private val urls = LinkedList(listOf("Patient?_sort=_lastUpdated"))
private val urls = LinkedList(listOf(
"Patient?_lastUpdated=gt2024-05-20T00:00:00.000+01:00&address-city=GENEVA&_sort=_lastUpdated",
"Encounter?_lastUpdated=gt2024-06-06T00:00:00.000+01:00&_sort=_lastUpdated",
//"Observation?_lastUpdated=gt2024-04-16T00:00:00.000+01:00&_sort=_lastUpdated"
))

override suspend fun getNextRequest(): DownloadRequest? {
var url = urls.poll() ?: return null
Expand Down Expand Up @@ -135,7 +140,8 @@ private fun affixLastUpdatedTimestamp(url: String, lastUpdated: String): String
downloadUrl = url
}

return downloadUrl
return url
//return downloadUrl
}

private fun Date.toTimeZoneString(): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,13 @@ import com.google.android.fhir.datacapture.validation.Invalid
import com.google.android.fhir.datacapture.validation.QuestionnaireResponseValidator
import java.util.UUID
import kotlinx.coroutines.launch
import org.hl7.fhir.r4.model.CodeableConcept
import org.hl7.fhir.r4.model.Extension
import org.hl7.fhir.r4.model.Identifier
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Reference
import org.openmrs.android.fhir.FhirApplication
import org.openmrs.android.fhir.fragments.AddPatientFragment

Expand Down Expand Up @@ -84,6 +88,19 @@ class AddPatientViewModel(application: Application, private val state: SavedStat
}
val patient = entry.resource as Patient
patient.id = generateUuid()


val identifierType = CodeableConcept().apply { text = "HSU ID" }
val identifier = Identifier();
identifier.value = "1111-1"
identifier.type = identifierType
patient.setIdentifier(mutableListOf(identifier));

val ref = Reference("Location/2d9378e3-b99f-42af-a109-f68395141bf3")
ref.setType("Location")
val ext = Extension("http://fhir.openmrs.org/ext/patient/identifier#location", ref);
patient.identifier.get(0).addExtension(ext);

fhirEngine.create(patient)
isPatientSaved.value = true
}
Expand Down

0 comments on commit e21843d

Please sign in to comment.