Pass synched Realm to other Activity - kotlin

When I try to access the synched Realm from e.g. Main Activity I always get the error lateinit var not initialised.
I can successful open a database on the device and also the synched Database. But because the open of the synched Database must be in "run blocking" I don't know how to access "synchedRealm" then. Can't pass it to Main Activity.
I am sure its kind of fundamental knowledge I don't get out of the Kotlin/Realm documentation because English is not my primary language.
Thank you for your help!!!
In another Activity: MyApp:
....
runBlocking {
// Neuen User Registrieren
// app.emailPasswordAuth.registerUser(email, pw)
// once registered, you can log in with the user credentials
val appid: String = "MYAppId"
val apikey: String = "MyApiKey"
val app: App = App.create(
AppConfiguration.Builder(appid)
.log(LogLevel.ALL)
.build()
)
val user_api = app.login(io.realm.kotlin.mongodb.Credentials.apiKey(apikey))
val config = SyncConfiguration.Builder(
user_api,
setOf(MyClass::class)
)
.initialSubscriptions { realm ->
add(
realm.query<PersonCollection>(
"MyField == $0",
"Mustermann"
),
"subscription name"
)
}
.build()
val realmSynced = Realm.open(config)
}
I tried also the above code in an object{} or the runblocking{} in an init{} block and dozend other things
In Mainactivity:
lateinit var realm:Realm
lateinit var realmSynched:Realm
...
realm=MyApp.Databaseobject.realm //Works for Database on device
realmSynched= ???? //How to initialise this ???

Related

Axonframework event scheduler keeps rerunning my event infinitely

So I want to create a simple food order service, but this service require some information from the other service so I use saga pattern. Here's how it should work if I order a food, first it will attempt to create order but if there's any error it will retry for 3 times and publish either success or failed event.
Here's the sample code.
#Saga
class OrderCreationSaga {
#Transient
#Autowired
private lateinit var commandGateway: CommandGateway
#Transient
#Autowired
private lateinit var eventScheduler: EventScheduler
#Transient
#Autowired
private lateinit var eventBus: EventBus
#Transient
#Autowired
private lateinit var scheduleToken: ScheduleToken
private lateinit var orderId: String
private var retryCounter = 1
#StartSaga
#SagaEventHandler(associationProperty = "orderId")
fun on(event: OrderCreationAttempted) {
this.orderId = event.orderId
eventBus.publish(GenericEventMessage(event.toOrderCreationRequested()))
}
#SagaEventHandler(associationProperty = "orderId")
fun on(event: OrderCreationRequested) {
try {
// send data to another service
orderCreationService.createOrder(event).block()
eventBus.publish(GenericEventMessage(
OrderCreationSuccess(
orderId = event.orderId
))
)
} catch (error: Throwable) {
// catching request error, retry for 3 times
if (this.retryCounter == 3) {
eventBus.publish(GenericEventMessage(
OrderCreationFailed(
orderId = this.orderId,
)
))
} else {
eventBus.publish(GenericEventMessage(
OrderCreationRetry(
orderId = event.orderId,
)
))
this.retryCounter++
}
}
}
#EndSaga
#SagaEventHandler(associationProperty = "orderId")
fun on(event: OrderCreationSuccess) {
// do the success job
}
#EndSaga
#SagaEventHandler(associationProperty = "orderId")
fun on(event: OrderCreationFailed) {
// do the failed job
}
#SagaEventHandler(associationProperty = "orderId")
fun on(event: OrderCreationRetry) {
val duration = Duration.ofSeconds(30)
val scheduleEvent = OrderCreationRequested(orderId = event.orderId)
scheduleToken = eventScheduler.schedule(duration, scheduleEvent)
}
}
But the weird thing happens so after it published a success event it will publish a OrderCreationRequested event again for some reason (I know this because I've checked the event log inside axonserver). This keeps looping infinitely, is this because my code or some configuration or could be something else?
So the problem was I forgot to set my username and password for my MongoDB and then someone just trying to delete all of my data including tracking token for axon-server. So because of the tracking token has been delete axon-server start creating the new one with 0 value which makes all the event start rerunning again and again. I solve this problem by just add the username and password for my MongoDB.

CUBA Platform push messages from backend to UI

i was wondering if it is possible to send messages from the backend (for example a running task that receives information from an external system) to the UI. In my case it needs to be a specific session (no broadcast) and only on a specific screen
plan B would be polling the backend frequently but i was hoping to get something more "realtime"
I was trying to work something out like this, but i keep getting a NotSerializableException.
#Push
class StorageAccess : Screen(), MessageListener {
#Inject
private lateinit var stationWSService: StationWebSocketService
#Inject
private lateinit var notifications: Notifications
#Subscribe
private fun onInit(event: InitEvent) {
}
#Subscribe("stationPicker")
private fun onStationPickerValueChange(event: HasValue.ValueChangeEvent<StorageUnit>) {
val current = AppUI.getCurrent()
current.userSession.id ?: return
val prevValue = event.prevValue
if (prevValue != null) {
stationWSService.remove(current.userSession.id)
}
val value = event.value ?: return
stationWSService.listen(current.userSession.id, value, this)
}
override fun messageReceived(message: String) {
val current = AppUI.getCurrent()
current.access {
notifications.create().withCaption(message).show()
}
}
#Subscribe
private fun onAfterDetach(event: AfterDetachEvent) {
val current = AppUI.getCurrent()
current.userSession.id ?: return
stationWSService.remove(current.userSession.id)
}
}
-- The callback interface
interface MessageListener : Serializable {
fun messageReceived(message: String);
}
-- The listen method of my backend service
private val listeners: MutableMap<String, MutableMap<UUID, MessageListener>> = HashMap()
override fun listen(id: UUID, storageUnit: StorageUnit, callback: MessageListener) {
val unitStationIP: String = storageUnit.unitStationIP ?: return
if (!listeners.containsKey(unitStationIP))
listeners[unitStationIP] = HashMap()
listeners[unitStationIP]?.set(id, callback)
}
The Exception i get is NotSerializableException: com.haulmont.cuba.web.sys.WebNotifications which happens during adding the listener to the backend: stationWSService.listen(current.userSession.id, value, this)
as far as i understand this is the place where the UI sends the information to the backend - and with it the entire status of the class StorageAccess, including all its members.
is there an elegant solution to this?
regards
There is an add-on that solves exactly this problem: https://github.com/cuba-platform/global-events-addon

Can I get a random user out of the firebase realtime database as chat partner as a second option besides a selected user?

I have a problem with coding a Chat application.
One of the planned features is getting connected with a random user from the database.
Currently I have one button that loads an overview of all users, you can chose one user, and you can chat with that person (message send/receive works, also when i close the app and open it again the messages are still viewable and saved).
For that, I have a NewMessageActivity, which on click on one user leads to the ChatLogActivity and takes the user information with it (toUser and USER_KEY).
Now my plan is to basically skip the NewMessage part and get right into the ChatLogActivity, and assign a random user to that.
I was thinking to just add something like an if/else to my code (so, if toUser is assigned by NewMessageActivity load that, otherwise load random), but I can't get it to work.
My users have each individual uid's, that get created randomly when signing up.
Here's my code:
companion object {
val TAG = "ChatLog"
}
val adapter = GroupAdapter<GroupieViewHolder>()
var toUser: User? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_log)
recyclerview_chat_log.adapter = adapter
keyboardManagement()
toUser = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
supportActionBar?.title = toUser?.username
listenForMessages()
send_button_chat_log.setOnClickListener {
Log.d(TAG, "Attempt to send message")
performSendMessage()
}
}
Here how I usually get the users for the chat, in case that is important:
val ref = FirebaseDatabase.getInstance().getReference("/users")
ref.addListenerForSingleValueEvent(object: ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<GroupieViewHolder>()
p0.children.forEach{
Log.d("NewMessage", it.toString())
val user = it.getValue(User::class.java)
if (user != null) {
adapter.add(UserItem(user))
}
}
adapter.setOnItemClickListener{ item, view ->
val userItem = item as UserItem
val intent = Intent(view.context, ChatLogActivity::class.java)
//intent.putExtra(USER_KEY, userItem.user!)
intent.putExtra(USER_KEY, userItem.user)
startActivity(intent)
//Zurück zum Main Menu statt zur User Auswahl
finish()
}
recyclerView_newmessage.adapter = adapter
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
class UserItem(val user: User): Item<GroupieViewHolder>() {
//wird aufgerufen für die einzelnen Userobjekte
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.itemView.username_textView_new_message.text = user.username
Picasso.get().load(user.profileImageURL).into(viewHolder.itemView.picture_imageView_new_message)
}
//Einzelne Zeilen gestalten
override fun getLayout(): Int {
return R.layout.user_row_new_messages
}
}
I'm still a beginner, so I'm pretty clueless what to do by now. If you have any ideas and could help me, I'd really appreciate that! :)
Thanks!

Upgrading some Corda3 source code to run on v4

First of all, I've only started learning corda 3 months ago so I've got some learning to do.
I've inherited some code that runs fine under Corda v3.3 but the customers want it to run on v4. I'm trying to follow the instructions on the main website. I've got an initiating flow which calls a subflow, which in turn calls a transponder flow.
The initiating flow:
#InitiatingFlow(version = 2)
#StartableByRPC
class TransferFlow(private val issuerName: String = "",
private val seller: String = "",
private val amount: BigDecimal = BigDecimal("0"),
private val buyer: String = "",
private val custodianNameOfBuyer: String = "",
private val notaryName: String = "") : FlowLogic<SignedTransaction>() {
#Suspendable
override fun call(): SignedTransaction {
subFlow(UpdateStatusOfTransferFlow(
sessions,
tokenTransferAgreement.linearId,
"Removed Tokens From Seller"))
}
}
class UpdateStatusOfTransferFlow(
private val sessions: Set<FlowSession>,
private val tokenTransferAgreementID: UniqueIdentifier,
private val newStatus: String) : FlowLogic<SignedTransaction>() {
#Suspendable
override fun call(): SignedTransaction {
sessions.size
val idQueryCriteria = QueryCriteria.LinearStateQueryCriteria(linearId = listOf(tokenTransferAgreementID))
val states = serviceHub.vaultService.queryBy<TokenTransferAgreement>(idQueryCriteria).states
if (states.size != 1) throw FlowException("Can not find a unique state for $tokenTransferAgreementID")
val inputStateAndRef = states.single()
val inputState = inputStateAndRef.state.data
val notary = inputStateAndRef.state.notary
val outputState = inputState.withNewStatus(newStatus)
val cmd = Command(TokenContract.Commands.UpdateStatusOfTransfer(),
inputState.participants.map { it.owningKey })
val txBuilder = TransactionBuilder(notary = notary)
txBuilder.addCommand(cmd)
txBuilder.addInputState(inputStateAndRef)
txBuilder.addOutputState(outputState, TokenContract.ID)
txBuilder.verify(serviceHub)
val ptx = serviceHub.signInitialTransaction(txBuilder)
val sessions2 = (inputState.participants.toSet() - ourIdentity).map { initiateFlow(it) }
return subFlow(CollectSignaturesFlow(ptx, sessions2))
}
}
And the responder:
#InitiatedBy(TransferFlowResponder::class)
class UpdateStatusOfTransferFlowResponder(private val session: FlowSession) : FlowLogic<Unit>() {
#Suspendable
override fun call() {
val tokenTransferAgreements = mutableListOf<TokenTransferAgreement>()
var isBuyer = true
var notary = CordaUtility.getNotary(serviceHub) ?: throw FlowException("An notary is expected!")
val signedTransactionFlow = subFlow(object : SignTransactionFlow(session) {
override fun checkTransaction(stx: SignedTransaction) = requireThat {
"There must be one output!" using (stx.tx.outputStates.size == 1)
val tokenTransferAgreement = stx.tx.outputStates.first() as TokenTransferAgreement
tokenTransferAgreements.add(tokenTransferAgreement)
notary = stx.notary ?: throw FlowException("An notary is expected!")
if (ourIdentity == tokenTransferAgreement.issuer) {
//checks go here
}
})
}
}
I believe I am supposed to add a call to ReceiveFinality flow at some point, however it only takes 1 session as an argument, not a list as I have here. Should I make multiple calls, one for each session? I am also not sure if the calls should go in the transponder or the UpdateStatusOfTransferFlow class.
Help here would be appreciated.
The FinalityFlow is mainly responsible for ensuring transactions are notarized, distributed accordingly and persisted to local vaults.
In previous versions of Corda, all nodes would by default accept incoming requests for finality.
From V4 onwards, you're required to write a ReceiveFinalityFlow to write your own processing logic before finality.
The way finality currently runs in Corda is the initiating node, as an intermediate step during finality, distributes notarised transaction to all other participants. Each of the participating nodes it sends to will only expect to receive a session from this node.
So where you might submit multiple sessions to the initiating FinalityFlow to include all the participants, the responding nodes will only ever receive just the one session from the initiator.
In the future, we may look at having the Notary distribute the notarized transaction to all participants, but even then, the ReceiveFinalityFlow would still only expect one session, this time from the Notary.

Kotlin - How do i set a sharedpreference code so that i open the closed app, it opens the last Activity, where i left it

I made two activities in my application, I want the app to be opened where I left off. In other words, not the default activity but the activity where I was when I last exited the app.
You could set a SplashActivity, where your app start, that will start other activities.
In this SplashActivity, you can set a var lastActivity, that will be a code to keep in which activity you were last time.
You get it with SharedPreference, and then go to the activity.
i.e :
String lastActivity = SharedPreference.getString(...) // I don't really remember the syntax
if (lastActivity == "HelloWorldActivity")
startActivity(HelloWorldActivity.getStartIntent(context))
else if (lastActivity == "GoodByeActivity")
startActivity(GoodByeActivity.getStartIntent(context))
Then, do NOT forget to edit your SharedPreference value EACH TIME you change activity.
I don't know if this is a good practice, but feel free to test this and give your think.
EDIT
First, you need to understand how is Shared Preference File. I think it looks like this :
"app_name"="Your app name"
"last_activity"="Your last activity"
"user_age"="23"
This could be the first activity you launch :
class SplashActivity : AppCompatActivity() {
var lastActivity = ""
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate()
/*
Here, we will get the SharedPreferencesFile.
Then, we get the value linked to the key TAG_LAST_ACTIVITY (set in companion object)
*/
val sharedPref = this.getSharedPreferences(getString(R.string.shared_preference_file_name), 0)
lastActivity = sharedPref.getString(TAG_LAST_ACTIVITY, "")
var activityToStart : AppCompatActivity? = null
if (lastActivity.isBlank())
activityToStart = YourActivityToStartAtFirstLaunch.getStartIntent(this)
else if (lastActivity.equals(TAG_ACTIVITY_ONE))
activityToStart = ActivityOne.getStartIntent(this)
else if (lastActivity.equals(TAG_ACTIVITY_TWO))
activityToStart = ActivityTwo.getStartIntent(this)
else if
... // Use as many as else if you need, but think about the "when" condition, it is better !
startActivity(activityToStart)
}
companion object {
private const val TAG_LAST_ACTIVITY = "last_activity"
private const val TAG_ACTIVITY_ONE = "activity_one"
private const val TAG_ACTIVITY_TWO = "activity_two"
}
}
And this could be your ActivityOne, for example :
class ActivityOne : AppCompatActivity() {
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate()
/*
Here, we will modify the variable LAST_ACTIVITY in the shared preferences file by setting it to "activity_one".
So, if the user quit this app now, you will know at next launch in which activity he stopped.
I think it is a better practice to set this in the onPause() or onStopped() method. Think about it ! ;)
*/
val sharedPrefEditor = this.getSharedPreferences(getString(R.string.shared_preference_file_name, 0)).edit()
sharedPrefEditor.putString(TAG_LAST_ACTIVITY, TAG_ACTIVITY_ONE)
sharedPrefEditor.apply()
}
companion object {
fun getStartIntent(context : Context) : Intent = Intent(context, ActivityOne()::class.java)
private const val TAG_ACTIVITY_ONE = "activity_one"
private const val TAG_LAST_ACTIVITY = "last_activity"
}
}
Do not forget to put your shared preference file name in your values/strings.xml file :
<string name="shared_preference_file_name">com.example.yourappname.sharedpref"</string>