Gatling scala - Unable to replace session variable in the request URI - gatling

I do have a session variable named AuctionId and couldn't replace AuctionId here in the POST request URI. Can you please advise what I am missing here?
object BidSubmission extends HttpUtil {
val orders_feeder = csv("data/Round-1.csv").circular
def orderSubmission: ChainBuilder =
pause(pauseBy(5) seconds)
.repeat(1) {
feed(orders_feeder)
.exec(postToUri("${Constants.orderSubmission_URL}/#{AuctionId}/base-orders/proxy-bid", "")
.queryParam("employeeId", "#{empNo}")
.body(StringBody(session => {
println(session)
println(session.attributes("empNo"))
val empNo = session.attributes("empNo").asInstanceOf[String]
val orderNo = session.attributes("orderNo").asInstanceOf[String]
println(s"\n\n\n $orderNo \n\n\n")
println("\n\n\n ${Constants.bidSubmission_URL}/#{AuctionId}/base-auctions/proxy-
bid \n\n\n")
var slotNos = orderNo.replace("[", "").replace("]", "").split(" +")
println(s"\n\n\n ${generatePayload(empNo, slotNos)} \n\n\n")
generatePayload(empNo, slotNos)
" "
}))
)
}
it prints uri like this instead of replacing AuctionId with the session variable value- https://order.com/golden/base-auction/system-override/auctions/#{AuctionId}/base-auctions/proxy-bid
trait HttpUtil extends StrictLogging {
def postToUri(uri: String, requestName: String, statusCode: Int = 201): HttpRequestBuilder = {
appendHeaders(http(requestName).post(uri)).check(status.is(statusCode))
}
private def appendHeaders(request: HttpRequestBuilder,
authScheme: String = config.auth.plannerToken): HttpRequestBuilder = {
request
.header("Authorization", authScheme)
.header("Content-Type", "application/json")
.header("Accept", "application/prs.hal-forms+json")
}
}

Related

How to parse array values from Json in Jmeter

For the below response I need to fetch the rideId and pass it to the next request in Jmeter.Also ,the API that generates below response should be executed until the eventType is HANDSHAKE.
[{"id":90856,"eventType":"HANDSHAKE","parameters":"{\"handshakeExpiration\":1669217518986,\"rideId\":3107}"}]
I am using the code :
import groovy.json.JsonSlurper;
def jsonSlurper=new JsonSlurper();
def apiDetailsArr=jsonSlurper.parse(prev.getResponseData())
def apiDetails=apiDetailsArr.size()>0?apiDetailsArr.get(0):null
def shouldRun = "1"
if(apiDetails!=null)
{
log.info("details",apiDetails.eventType+"")
if(apiDetails.eventType="HANDSHAKE"){
shouldRun="0"
}
def object=jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz",object+"")
def id=object.rideId;
log.info("id",id+"")
vars.put("id", id+"")
}
else{
shouldRun="1"`enter code here`
}
`Condition for while controller : `${__javaScript( "${shouldRun}" != "0",)}``
All your log.info function calls cause syntax errors, you can see it yourself in (surprise!) the jmeter.log file
I fail to see where you're assigning shouldRun JMeter Variable which is used in the While Controller
Suggested code change:
import groovy.json.JsonSlurper;
def jsonSlurper = new JsonSlurper();
def apiDetailsArr = jsonSlurper.parse(prev.getResponseData())
def apiDetails = apiDetailsArr.size() > 0 ? apiDetailsArr.get(0) : null
def shouldRun = "1"
if (apiDetails != null) {
log.info("details", apiDetails.eventType + "")
if (apiDetails.eventType = "HANDSHAKE") {
shouldRun = "0"
}
def object = jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz" + object)
def id = object.rideId;
log.info("id" + id)
vars.put("id", id as String)
} else {
shouldRun = "1"
}
vars.put("shouldRun", shouldRun)
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Scala Akka RestartSource onFailuresWithBackoff not working complaining dead letters encountered

I have created a RetryFlow like below,following this article https://doc.akka.io/docs/akka/current/stream/operators/RetryFlow/withBackoff.html
private val httpFlow: Flow[HttpRequest, HttpResponse, Any] =
Http().outgoingConnection(host, port)
val retryFlow: Flow[HttpRequest, HttpResponse, Any] =
RetryFlow.withBackoff(minBackoff = 10.millis, maxBackoff = 5.seconds, randomFactor = 0d, maxRetries = 20, httpFlow)(
decideRetry = {
case (request: HttpRequest, response) =>
response.status match {
case StatusCodes.OK => Some(request)
case _ => None
}
})
And then processing flow like
val request = Post(Uri(path), some_json_payload)(
stringMarshaller(MediaTypes.`application/json`),
system.executionContext
)
httpClient.processRequest(request, retryFlow) map (...)
My http client looks like below, added a RestartSettings and restarting source on onFailuresWithBackoff
class HttpClient(implicit val system: ActorSystem[_]) {
implicit val materializer: Materializer = Materializer(system)
private def checkSuccess(response: HttpResponse, path: String): Either[Throwable, HttpResponse] =
Either.cond(
response.status == StatusCodes.OK,
response,
new Throwable(s"Could not GET $path, Service returned ${response.status.toString()}"),
)
private def httpRequest(
request: HttpRequest,
flow: Flow[HttpRequest, HttpResponse, Any],
): Future[Either[Throwable, HttpResponse]] =
Source.single(request).via(flow)
.runWith(Sink.head) map { response =>
checkSuccess(response, request.uri.path.toString())
}
private def unmarshallString(response: Either[Throwable, HttpResponse]): Future[Either[Throwable, String]] =
response.fold(
err => Future(err.asLeft[String]),
r => Unmarshal(r.entity).to[String].map(_.asRight[Throwable]),
)
def processRequest(request: HttpRequest, flow: Flow[HttpRequest, HttpResponse, Any]): Future[Enclosed[Json]] =
httpRequest(request, flow) flatMap unmarshallString map (_.flatMap(parse))
}
I am pretty new especially in akka , what I am missing here .

Trying to display name of users on support action bar

Please i am new to kotlin and i have been trying to retrive the fullname of my users in the data base after using getStringExtra so i can use each of them for the title of my support action bar but the value it returns an empty value.
val name = intent.getStringExtra("fullname")
val receiverUid = intent.getStringExtra("uid")
val senderUid = FirebaseAuth.getInstance().currentUser?.uid
mDbRef = FirebaseDatabase.getInstance().getReference()
senderRoom = receiverUid + senderUid
receiverRoom = senderUid + receiverUid
supportActionBar?.title = name
Here is how i am sending name and receiverUid to my database
sendButton.setOnClickListener{
val message = messageBox.text.toString()
val messageObject = Message(message, senderUid)
val name = name.toString()
val receiverUid = receiverUid.toString()
val chatlistObject = ModelChatList(name, message, receiverUid)
mDbRef.child("chats").child(senderRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mDbRef.child("chats").child(receiverRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mDbRef.child("Chatlist").push().setValue(chatlistObject)
}
}
messageBox.setText("")
But when i try to retrive my ModelChatlist object it returns only two values leaving out the receivername as shown in the ModelChatlist below
class ModelChatList {
private var receivername:String = ""
private var lastmessage:String = ""
private var uid:String = ""
constructor(){}
constructor(receivername: String, lastmessage:String, uid:String){
this.receivername = receivername
this.lastmessage = lastmessage
this.uid =uid
}
fun getReceivername(): String{
return receivername
}
fun setReceivername(receivername: String){
this.receivername= receivername
}
fun getUid(): String{
return uid
}
fun setUid(uid: String){
this.uid= uid
}
fun getLastmessage(): String{
return lastmessage
}
fun setLastmessage(lastmessage: String){
this.lastmessage= lastmessage
}
}
In case you are wondering, "fullname" is in my database as the name the users enter when they sign up. Thank You

Is there any way to zip two or more streams with order of event time in Flink?

Suppose we have a stream of data with this format:
example of input data stream:
case class InputElement(key:String,objectType:String,value:Boolean)
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
val inputStream:DataSet[InputElement] = env.fromElements(
InputElement("k1","t1",true)
,InputElement("k2","t1",true)
,InputElement("k2","t2",true)
,InputElement("k1","t2",false)
,InputElement("k1","t2",true)
,InputElement("k1","t1",false)
,InputElement("k2","t2",false)
)
it is semantically equal to have these streams:
val inputStream_k1_t1 = env.fromElements(
InputElement("k1","t1",true),
InputElement("k1","t1",false)
)
val inputStream_k1_t2 = env.fromElements(
InputElement("k1","t2",false),
,InputElement("k1","t2",true)
)
val inputStream_k2_t1 = env.fromElements(
InputElement("k2","t1",true)
)
val inputStream_k2_t2 = env.fromElements(
InputElement("k2","t2",true),
InputElement("k2","t2",false)
)
I want to have an output type like this:
case class OutputElement(key:String,values:Map[String,Boolean])
expected output data stream for the example input data:
val expectedOutputStream = env.fromElements(
OutputElement("k1",Map( "t1"->true ,"t2"->false)),
OutputElement("k2",Map("t1"->true,"t2"->true)),
OutputElement("k1",Map("t1"->false,"t2"->true)),
OutputElement("k2",Map("t2"->false))
)
==========================================
edit 1:
after some considerations about the problem the subject of the question changed:
I want to have another input stream that shows which keys are subscribed to which object types:
case class SubscribeRule(strategy:String,patterns:Set[String])
val subscribeStream: DataStream[SubscribeRule] = env.fromElements(
SubscribeRule("s1",Set("p1","p2")),
SubscribeRule("s2",Set("p1","p2"))
)
now I want to have this output:
(the result stream does not emit any thing till all the subscribed objectType are received:
val expectedOutputStream = env.fromElements(
OutputElement("k1",Map( "t1"->true ,"t2"->false)),
OutputElement("k2",Map("t1"->true,"t2"->true)),
OutputElement("k1",Map("t1"->false,"t2"->true)),
// OutputElement("k2",Map("t2"->false)) # this element will emit when a k2-t1 input message recieved
)
App.scala:
import org.apache.flink.api.common.state.MapStateDescriptor
import org.apache.flink.api.scala.createTypeInformation
import org.apache.flink.streaming.api.datastream.BroadcastStream
import org.apache.flink.streaming.api.scala.{DataStream, KeyedStream, StreamExecutionEnvironment}
object App {
case class updateStateResult(updatedState:Map[String,List[Boolean]],output:Map[String,Boolean])
case class InputElement(key:String,objectType:String,passed:Boolean)
case class SubscribeRule(strategy:String,patterns:Set[String])
case class OutputElement(key:String,result:Map[String,Boolean])
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
// checkpoint every 10 seconds
val subscribeStream: DataStream[SubscribeRule] = env.fromElements(
SubscribeRule("s1",Set("p1","p2")),
SubscribeRule("s2",Set("p1","p2"))
)
val broadcastStateDescriptor =
new MapStateDescriptor[String, Set[String]]("subscribes", classOf[String], classOf[Set[String]])
val subscribeStreamBroadcast: BroadcastStream[SubscribeRule] =
subscribeStream.broadcast(broadcastStateDescriptor)
val inputStream = env.fromElements(
InputElement("s1","p1",true),
InputElement("s1","p2",true),
InputElement("s2","p1",false),
InputElement("s2","p2",true),
InputElement("s2","p2",false),
InputElement("s1","p1",false),
InputElement("s2","p1",true),
InputElement("s1","p2",true),
)
val expected = List(
OutputElement("s1",Map("p2"->true,"p1"->true)),
OutputElement("s2",Map("p2"->true,"p1"->false)),
OutputElement("s2",Map("p2"->false,"p1"->true)),
OutputElement("s1",Map("p2"->true,"p1"->false))
)
val keyedInputStream: KeyedStream[InputElement, String] = inputStream.keyBy(_.key)
val result = keyedInputStream
.connect(subscribeStreamBroadcast)
.process(new ZippingFunc())
result.print
env.execute("test stream")
}
}
ZippingFunc.scala
import App.{InputElement, OutputElement, SubscribeRule, updateStateResult}
import org.apache.flink.api.common.state.{ MapState, MapStateDescriptor, ReadOnlyBroadcastState}
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction
import org.apache.flink.util.Collector
import java.util.{Map => JavaMap}
import scala.collection.JavaConverters.{iterableAsScalaIterableConverter, mapAsJavaMapConverter}
class ZippingFunc extends KeyedBroadcastProcessFunction[String, InputElement,SubscribeRule , OutputElement] {
private var localState: MapState[String,List[Boolean]] = _
private lazy val broadcastStateDesc =
new MapStateDescriptor[String, Set[String]]("subscribes", classOf[String], classOf[Set[String]])
override def open(parameters: Configuration) {
val localStateDesc: MapStateDescriptor[String,List[Boolean]] =
new MapStateDescriptor[String, List[Boolean]]("sourceMap1", classOf[String], classOf[List[Boolean]])
localState = getRuntimeContext.getMapState(localStateDesc)
}
def updateVar(objectType:String,value:Boolean): Option[Map[String, Boolean]] ={
val values = localState.get(objectType)
localState.put(objectType, value::values)
pickOutputs(localState.entries().asScala).map((ur: updateStateResult) => {
localState.putAll(ur.updatedState.asJava)
ur.output
})
}
def pickOutputs(entries: Iterable[JavaMap.Entry[String, List[Boolean]]]): Option[updateStateResult] = {
val mapped: Iterable[Option[(String, Boolean, List[Boolean])]] = entries.map(
(x: JavaMap.Entry[String, List[Boolean]]) => {
val key: String = x.getKey
val value: List[Boolean] = x.getValue
val head: Option[Boolean] = value.headOption
head.map(
h => {
(key, h, value.tail)
}
)
}
)
sequenceOption(mapped).map((x: List[(String, Boolean, List[Boolean])]) => {
updateStateResult(
x.map(y => (y._1, y._3)).toMap,
x.map(y => (y._1, y._2)).toMap
)
}
)
}
def sequenceOption[A](l:Iterable[Option[A]]): Option[List[A]] =
{
l.foldLeft[Option[List[A]]](Some(List.empty[A]))(
(acc: Option[List[A]], e: Option[A]) =>{
for {
xs <- acc
x <- e
} yield x :: xs
}
)
}
override def processElement(value: InputElement, ctx: KeyedBroadcastProcessFunction[String, InputElement, SubscribeRule, OutputElement]#ReadOnlyContext, out: Collector[OutputElement]): Unit = {
val bs: ReadOnlyBroadcastState[String, Set[String]] = ctx.getBroadcastState(broadcastStateDesc)
if(bs.contains(value.key)) {
val allPatterns: Set[String] = bs.get(value.key)
allPatterns.map((patternName: String) =>
if (!localState.contains(patternName))
localState.put(patternName, List.empty)
)
updateVar(value.objectType, value.passed)
.map((r: Map[String, Boolean]) =>
out.collect(OutputElement(value.key, r))
)
}
}
// )
override def processBroadcastElement(value: SubscribeRule, ctx: KeyedBroadcastProcessFunction[String, InputElement, SubscribeRule, OutputElement]#Context, out: Collector[OutputElement]): Unit = {
val bs = ctx.getBroadcastState(broadcastStateDesc)
bs.put(value.strategy,value.patterns)
}
}

JPA question (Scala using)

OpenJPA and Scala question.
There are 2 tables in database (h2) - tasks and taskLists.
TaskList contains collection ArrayList.
Each TaskList can contain tasks from another TaskLists
When taskX modified in TaskList1 it have to be modified in TaskList2, if it contains taskX.
How to implement this?
I can add new task to task list and save it to DB, but when I try to add taskX from TaskList1 tasks collection to TaskList2 tasks collection and persist it, taskX is not persisted in db.
Example:
1. Adding task1 to taskList1 and task2 to taskList2 will result:
TaskList1: [task1]
TaskList2: [task2]
2. Adding task2 to taskList1 will result:
TaskList1: [task1]
3. Adding task3 to taskList1 and task4 to taskList2 will result:
TaskList1: [task1, task3]
TaskList2: [task2, task4]
What is wrong?
Task class:
import _root_.javax.persistence._
import org.apache.openjpa.persistence._
#Entity
#Table(name="tasks")
#ManyToMany
class CTask (name: String) {
def this() = this("new task")
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
var id: Int = _
var title: String = name
def getId = id
def getTitle = title
def setTitle(titleToBeSet: String) = title = titleToBeSet
override def toString: String = title
}
TaskList class:
import _root_.javax.persistence._
import _root_.java.util.ArrayList
import org.apache.openjpa.persistence._
#Entity
#Table(name="tasklists")
class CTaskList(titleText: String) {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
var id: Int = _
#Column(nullable = false)
var title: String = titleText
#ManyToMany
var tasks: ArrayList[CTask] = _;
var tags: String = ""
var rank: Int = 0
def getTasks = tasks
def this() = this("new task list")
def createTasks: ArrayList[CTask] = {
tasks = new ArrayList[CTask]
tasks
}
def getID = id
def getTags = tags
def setTags(tagsParam: String) = tags = tagsParam
def getRank = rank
def setRank(rankParam: Int) = rank = rankParam
def getTitle: String = title
def getTaskById(index: Int): CTask = {
null
}
def equals(anotherTaskList: CTaskList): Boolean = {
if (anotherTaskList == null) return false
if (anotherTaskList.getTasks == null)
return id == anotherTaskList.getID && title == anotherTaskList.getTitle && tags == anotherTaskList.getTags && rank == anotherTaskList.getRank && tasks == null;
else
return id == anotherTaskList.getID && title == anotherTaskList.getTitle && tags == anotherTaskList.getTags && rank == anotherTaskList.getRank && tasks != null && tasks.size == anotherTaskList.getTasks.size
}
def addTask(taskToBeAdded: CTask): Int = {
if (tasks == null)
tasks = new ArrayList[CTask]
tasks.add(taskToBeAdded)
tasks.indexOf(taskToBeAdded)}
def printTasks = println("TaskList's " + this + " tasks: " + tasks)
}
As far as I know, Many-To-Many association (as specified in your mapping annotations) implies association table between two entities (i.e. #JoinTable annotation should be specified).

Resources