having error when represent data to the platform - java

I get this error:
Message: exception
Details: 'Cannot get property \'data\' on null object
Here’s my code:
import javax.xml.bind.DatatypeConverter;
import com.carriots.sdk.utils.BasicHttp;
def APIKEY = '1c7021dfcc02e4f52a8db39'
//// Data Fetching ////
def inc_data = context.data.data;
def d1 = inc_data[0..1];
//// Custom Rules declaration ////
def device_id = context.data.id;
def devicename = device_id + '23A2B#User.User';
def rssi = context.data.rssi;
def avgSnr = context.data.avgSnr;
def D1 = Long.parseLong(d1, 16)
//// Filter Status ////
if (D1 >= 1) {
fltstatus = "motion detected";
} else {
fltstatus = "No motion";
}
//// Payload ////
// Build Stream to persist.
// I think the error from the data variable but I do not why...
def data = '{"motion detection": "' + fltstatus + '"}'
def payload_data = '{"at": "now", "protocol": "v2", "device": "' +
devicename + '", "data": "' + data +'"}'
def basicHttp = new BasicHttp();
basicHttp.verb = "POST";
basicHttp.payload = payload_data;
basicHttp.url = "http://api.m.om/status/";
basicHttp.headers = [
"Content-type": "application/json",
"Accept": "application/json",
"User-Agent": "Listener-Carriots",
"carriots.apikey": APIKEY
]
basicHttp.send();

Your first use of data as a property is this line:
def inc_data = context.data.data;
^ ^
(1) (2)
Since you use it twice, it’s impossible to know which use is throwing the exception. I recommend breakpointing this line, then using your debugger to determine that:
context is not null
context.data is not null

Related

Cant fill json array to array list android development

I was trying to send json array from my web into an arraylist in a class with volley libarary
Here is array that i want to be filled
i want to replace dummy data in function getBestSelling() with data from web
Filename = DummyDataSource.kt (it is just plain kotlin class)
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
val dummy1 = ProductEntity(name = "Bell Pepper Red", description = "1kg, Priceg",
price = 20000,
picture = R.drawable.iv_pepper_red,
id = 5
)
val dummy2 = ProductEntity(name = "Beef bone", description = "1kg, Priceg",
price = 25000,
picture = R.drawable.iv_beef_bone,
id = 6
)
val dummy3 = ProductEntity(name = "Boiler Chicken", description = "1kg, Priceg",
price = 15000,
picture = R.drawable.iv_boiler_chicken,
id = 7
)
val dummy4 = ProductEntity(name = "Ginger", description = "250gm, Priceg",
price = 22000,
picture = R.drawable.iv_ginger,
id = 4
)
val data = listOf(dummy1, dummy2, dummy3, dummy4)
return Observable.just(ArrayList(data))
}
Here are what i do to get array filled
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
The error come from line " var rq : RequestQueue = Volley.newRequestQueue(this)"
it says
"Type mismatch: inferred type is DummyDataSource but Context! was expected"
so i copied this code
fun getdata(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
into oncreate in the main activity. But because of that i cant fill array within getBestSelling() in DummyDataSource.kt because the function getdata() only return data to oncreate
Is there any way to make data go to getBestSelling() in DummyDataSource.kt ?
Move your function back out of onCreate and replace "this" with a context reference (requreContext() or create a Context var in onCreate to reference)

Services set with status code different from 200 are failed

My goal is to test my services depending on their service HTTP status.
When I launch my request, just services set by the 200 value succeed but another status like 400, 500, etc. failed that can be seen on the logs.
I am using soaPUI for a testing application located on the Tomcat server. The tracks of my requests are logged on another application before that test, the HTTP status was unique and set for all called services.
Now, for my test I have to dissociate the HTTP status code of my services, that is to each service with its own HTTP status depending on my tests needs.
code:
import com.eviware.soapui.impl.rest.mock.RestMockResult
import java.nio.charset.Charset
import com.eviware.soapui.model.mock.MockRunListener
import groovy.json.JsonSlurper
httpStatus = 200
def writeOut(fileEndPath, mockResult, method) {
def jsonFile = new File(dataDir + fileEndPath)
log.info "jsonFile " + jsonFile
if("GET".equalsIgnoreCase(method)){
mockRequest.httpResponse.status = httpStatus
mockRequest.httpResponse.setContentType("application/json")
mockRequest.httpResponse.writer.print(jsonFile.getText("UTF-8"))
mockRequest.httpResponse.writer.flush()
}
}
def isFileToReturnExist(fileToReturn){
def fileExist = false
if(fileToReturn != null){
def fileToTest = new File(dataDir + fileToReturn)
if( fileToTest.exists() && fileToTest.canRead()){
fileExist = true
}
}
return fileExist
}
dataDir = new File(context.getMockService().getProject().path).parent
def services = ["Service1", "Service2", "Service3", "Service4",
"Service5", "Service6", "Service7","Service8"]
def status = [200, 400, 200, 200, 400, 200, 200, 200]
def temp =
mockRequest.getHttpRequest().getQueryString().split("fields=")
if ( temp.size() == 2){
temp = temp[1].split("&")
if ( temp.size() > 0){
infos = temp[0]
for(int i=0; i< services.size; i++){
el = services[i]
if ( infos.split(",").size() > 1 && (infos.split(",")
[1]== el || infos.split(",")[0]== el)){
infos = el
httpStatus = status[i]
break;
}
}
}
}
inf = infos.split(",")
log.info inf.size()
def docroot = "/pns/"+infos
def method = mockRequest.getHttpRequest().getMethod();
def queryString = mockRequest.getHttpRequest().getPathInfo()
log.info "method " + method
log.info "queryString " + queryString
if(queryString != null){
def list = queryString.trim().split("/")
def credValue = list[list.size()-1].tokenize('|')[0]
def typecredential = ""
def lstcredtemp = list[list.size()-2].tokenize('|')
if ( lstcredtemp.size() > 0){
typecredential = lstcredtemp[0] + "_"
}
if("GET".equalsIgnoreCase(method)){
fileToReturn = docroot + "/Response_" + typecredential +
credValue + ".json"
}
}
if(!isFileToReturnExist(fileToReturn)){
log.info "le fichier " + fileToReturn + " n'existe pas"
fileToReturn = docroot+"/error.json"
}
RestMockResult mockResult = new RestMockResult( mockRequest )
if (fileToReturn != null) {
writeOut(fileToReturn, mockResult, method)
}
log.info typecredential + " fileToReturn : " + fileToReturn
return mockResult
The log application is supposed to trace for services with status 200 a START line and STOP line with OK.
For services with status code 400 (according to the code) are traced with a START line and a STOP line with KORG, the return code and the description of the error.
But my actual results are that for services with the status code 400, I get just the START line, but not the STOP line with error description and so on.
NTL;NTL;FRO;GetMyServices;START;;;IBTIs;IBTIt;.......;
NTL;FRO;SP;getPns[Service1];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service1];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service5];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service2];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];START;;;IBTIs;IBTIt;
NTL;FRO;ADVISE;getProposal;START;;;IBTIs;IBTIt;
NTL;FRO;SPX;getProposal;STOP;OK;200;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service6];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];STOP;KORG;Mapping
exception;IBTIs;IBTIt;Mapping exception reponse pnsGatape;
NTL;FRO;SP;getPns[Service6];STOP;OK;;IBTIs;IBTIt;
NTL;NTL;FRO;GetMyServices;STOP;OK;;IBTIs;IBTIt;....

SoapUI How to get Request and Response size for each TestStep

I have a bit of Groovy script that loops through the test steps in the current test case and sums the response time for each step and stores it in a custom property on the test case.
I am now trying to do the same for each test step's request and response size but cannot seem to get it to work.
def TestCase = testRunner.getTestCase()
def CurrentTestStep = context.testCase.getTestStepAt(context.getCurrentStepIndex()).getLabel()
def StepList = TestCase.getTestStepList().name - CurrentTestStep
def ResponseTime = 0
def RequestSize = 0
def ResponseSize = 0
StepList.each
{ Step ->
try
{
ResponseTime = ResponseTime + testRunner.testCase.testSteps[Step].testRequest.response.timeTaken
}
catch(Exception expObj)
{
}
}
testRunner.testCase.setPropertyValue("Test_Case_Response_Time", ResponseTime.toString())
You can us below statement for the Response size.
log.info "Size of " + Step + "is " + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
the full code would be
def TestCase = testRunner.getTestCase()
def CurrentTestStep =
context.testCase.getTestStepAt(context.getCurrentStepIndex()).getLabel()
def StepList = TestCase.getTestStepList().name - CurrentTestStep
def ResponseTime = 0
def RequestSize = 0
def ResponseSize = 0
StepList.each
{
Step ->
try
{
log.info "Size of " + Step + "is " + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
ResponseSize= ResponseSize + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
}
catch(Exception e)
{
}
}
testRunner.testCase.setPropertyValue("Test_Case_Response_Size", ResponseSize.toString())
For request size i was not able to find the statement to get size. will Add once get it.

How to Extract vector in session?

I have saved vector in session and I want to use random value from the vector but dont know how to extract value in session.
Errors:
'httpRequest-6' failed to execute: Vector(437420, 443940, 443932,
437437, 443981, 443956, 443973, 443915, 437445) named 'termIds' does
not support .random function
And
In 2nd scenario It passes vector in get request like this way, http://someurl/api/thr/Vector(435854)/terms/Vector(437420, 443940,
443932, 437437, 443981, 443956, 443973, 443915, 437445)
instead of using
http://someurl/api/thr/435854/terms/443973
::Here is my script::
class getTerm extends Simulation {
val repeatCount = Integer.getInteger("repeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val turl = System.getProperty("turl", "some url")
val httpProtocol = http
.baseURL("http://" + turl)
val headers_10 = Map("Content-Type" -> """application/json""")
var thrIds = ""
var termIds = ""
// Scenario - 1
val getTerms = scenario("Scn 1")
.exec(http("list_of_term")
.get("/api/abc")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll.saveAs("thrIds"))
)
.exec(http("get_all_terms")
.get("""/api/thr/${thrIds.random()}/terms""")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll.saveAs("termIds"))
)
.exec(session => {
thrIds = session("thrIds").as[Long].toString
termIds = session("termIds").as[Long].toString
println("***************************************")
println("Session ====>>>> " + session)
println("Ths ID ====>>>> " + thrIds)
println("Term ID ====>>>> " + termIds)
println("***************************************")
session}
)
// Scenario - 2
// Want to extract vectors here and pass its value into get call
val getKnownTerms = scenario("Get Known Term")
.exec(_.set("thrIds", thrIds))
.exec(_.set("termIds", termIds))
.repeat (repeatCount){
exec(http("get_k_term")
.get("""/api/thr/${thrIds}/terms/${termIds.random()}""")
.headers(headers_10))
}
val scn = List(getTerms.inject(atOnceUsers(1)), getKnownTerms.inject(nothingFor(20 seconds), atOnceUsers(userCount)))
setUp(scn).protocols(httpProtocol)
}
Here is the solution which may help others.
class getTerm extends Simulation {
val repeatCount = Integer.getInteger("repeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val turl = System.getProperty("turl", "some url")
val httpProtocol = http
.baseURL("http://" + turl)
val headers_10 = Map("Content-Type" -> """application/json""")
// Change - 1
var thrIds: Seq[String] = _
var termIds: Seq[String] = _
// Scenario - 1
val getTerms = scenario("Scn 1")
.exec(http("list_of_term")
.get("/api/abc")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll
.transform { v => thrIds = v; v }
.saveAs("thrIds"))
)
.exec(http("get_all_trms")
.get("""/api/thr/${thrIds.random()}/terms""")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll
.transform { v => termIds = v; v }
.saveAs("termIds"))
)
// Scenario - 2
val getKnownTerms = scenario("Get Known Term")
.exec(_.set("thrIds", thrIds))
.exec(_.set("termIds", termIds))
.repeat (repeatCount){
exec(http("get_k_term")
.get("""/api/thr/${thrIds.random()}/terms/${termIds.random()}""")
.headers(headers_10))
}
val scn = List(getTerms.inject(atOnceUsers(1)), getKnownTerms.inject(nothingFor(20 seconds), atOnceUsers(userCount)))
setUp(scn).protocols(httpProtocol)
}

How to Evaluate using "groovy.util.Eval" class

I am unable to evaluate the following statement in groovy:
def responseAct = new JsonSlurper().parseText(testRunner.testCase.getTestStepByName(Step).getPropertyValue("response"));
String x = "response.errorNumber";
String evaluate = "def value = responseAct." + x;
Eval.me(evaluate);
Error I am getting is:
groovy.lang.MissingPropertyException
It should be:
def responseAct = [
response: [
errorNumber: 2
]
]
String x = "response.errorNumber";
String evaluate = "def value = $responseAct." + x
Eval.x(responseAct, evaluate)
#Opal, Yeah... got through the problem. Its just the variable for the JSON data should have been a object of JsonSlurper. Here is an working example:
def objResponse = new JsonSlurper().parseText(testRunner.testCase.getTestStepByName("Step Name for Rest Step").getPropertyValue("response"));
String res = "response.errorNumber";
String evaluate = "x." + res;
String value = Eval.x(objResponse, evaluate);

Categories

Resources