How to provide a variable when reading sessionScope in cs javascipt? - xpages

I want to read the value from a sessionScope in clientside javascript. However I need to calculate the key for which value to collect e.g.:
var sessionKey = "type_" + userLocale;
var keyword_type = '#{javascript: sessionScope.get(' + sessionKey + ').get('values')}';
I get the error message:
Error while executing JavaScript computed expression Script
interpreter error, line=1, col=39: 'sessionScope.get()' is null
1: sessionScope.get(' + sessionKey + ').get('values')
Is there any way I can provide a variable when I try to read the sessionScope?

Related

TypeError: process_session() missing 1 required positional argument: 'session'

I am facing this error I tried everything, I deployed this function as a google cloud function, but when I am running the triggering URL I am getting an error
Request cannot be handled
Logs are
TypeError: process_session() missing 1 required positional argument: 'session'
at call_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:261)
at invoke_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:268)
at run_http_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:402)
Function code
def process_session(self, session, utc_offset=0):
s = {}
try:
edfbyte, analysis = process_session(session, utc_offset)
report_json, quality = process_analysis(analysis, session.ref.id)
# save the EDF
path = 'Users/' + session.ref.get("uid") + '/session-' + session.ref.get("sessionId") + '.edf'
path_report = 'Users/' + session.ref.get("uid") + '/session-' + session.ref.get("sessionId") + '.json'
bucket = storage.bucket("......")
bucket.blob(path).upload_from_string(edfbyte, content_type='application/octet-stream')
bucket.blob(path_report).upload_from_string(report_json, content_type='application/json')
# update session
s = session.to_dict()
s[u'macid'] = analysis['header']['macid']
s[u'quality'] = quality
s[u'edfPath'] = path
s[u'reportPath'] = path_report
s[u'timestamp'] = dateutil.parser.parse(analysis['header']['startdate'])
self.db.collection(u'ProcessedSessions').document(session.ref.id).set(s)
try:
self.db.collection(u'UnprocessedSessions').document(session.ref.id).delete()
#session.ref.reference.delete()
except:
pass
return True, 0
except Exception as e:
traceback.print_exc()
s = session.to_dict()
if u'attempt' in s:
attempt = s['attempt']
else:
attempt = 0
self.db.collection(u'UnprocessedSessions').document(session.ref.id).set({u'attempt': attempt + 1}, merge=True)
return False, attempt + 1
You are trying to pass 3 parameters in a HTTP Trigger, Python only accepts 1 parameter wich is a Flask Request Object.
HTTP Functions
Your function is passed a single parameter, (request), which is a
Flask Request object. Return any value from your function that can be
handled by the Flask make_response method. The result will be the HTTP
response.
You can try this to invoke your function:
def functionx (request):
# the GCF always receive only 1 paramater an HTTP request object (flask request)
# you need to get the parameter from the request
# after that you can call your method
process_session(param1,param2,param3)
def process_session(self, session, utc_offset=0):
#dosomenthing
print ("some code here")
Or if you need to use more parameters for your entry point, you can use a Background function.
Background Functions
Background functions are passed arguments holding
data associated with the event that triggered the function's
execution. In the Python runtime, your function is passed the
arguments (data, context)
Is this all part of def process_session? I can't see indentation.
Is it inside a class-object?
Maybe try in line 4:
edfbyte, analysis = self.process_session(session, utc_offset)
The given error signals that you haven't referenced the class-object.

Java Application taking long time to execute Groovy scripts which are precomplied

I have my groovy script precomplied on server start (I have stored groovy scripts as varchar in DB) up like below in Map ,
final Binding sharedData = new Binding();
final GroovyShell shell = new GroovyShell(sharedData);
script= shell.parse(rs.getString("VALIDATION_SCRIPT"));
Now when checking the validation on input records based on specified validation id i try to execute the precompiled script as below.
Script scrpt = Validation.getScript(); //getting from cache
scrpt.getBinding().setVariable("attributes", objects);
scrpt.getBinding().setVariable("tools", scrpt);
GroovyResponse gr = scrpt.evaluate("tools.valid(attributes)");
but here my application takes long time to evaluate..i guess heap size also gets increase and GC takes place. Can any one help me if there are better way to do it. with out impacting the performance.
one of My groovy script :
import com.fis.derivatives.utility.generic.model.GroovyResponse;
def valid(Map mapInput){
GroovyResponse obj = new GroovyResponse()
if(mapInput.inputVal.equals("1")){
obj.setStatus(true) ;
obj.setResultValue("B") ;
} else if(mapInput.inputVal.equals("2")){
obj.setStatus(true) ;
obj.setResultValue("S") ;
}else{
obj.setStatus(false);
obj.setComment("Error : Unable to extract BUY_SELL. Please check BS value "+mapInput.inputVal+".")
}
return obj;
}
1 - I have doubts about your cache. getting from cache without any key is strange...
Script scrpt = Validation.getScript(); //getting from cache
2 - rework a little the call of groovy:
Script scrpt = Validation.getScript(); //getting from cache
//we will pass attributes as a parameter to method
//scrpt.getBinding().setVariable("attributes", objects);
//not necessary to pass to script link to itself
//scrpt.getBinding().setVariable("tools", scrpt);
GroovyResponse gr = scrpt.invokeMethod​("valid", objects);

Why JMeter varibles aren't set from JSR223 Groovy Assertion?

I'm trying to set Jmeter variables extracted from Jmeter properties inside JSR223 Groovy Assertion.
Jmeter properties in which I'm interested looks like:
...
created_blob_A_6= fde65de0-3e32-11e8-a5b4-3906549016d8
created_blob_A_8= fef92d70-3e32-11e8-a5b4-3906549016d8
created_blob_A_9= ff775e20-3e32-11e8-bac3-e51250ffea15
created_blob_B_1= fd7302a0-3e32-11e8-a5b4-3906549016d8
created_blob_B_10= 00141350-3e33-11e8-bac3-e51250ffea15
...
In order to extract values from Jmeter properties, I've created JSR223 Groovy the following Assertion script:
def readParamPrefix = 'created_blob'
def writeParamPrefix = 'blob_to_delete'
def chucnkTypes = 'A'..'E'
def newBlobCounter = 1
chucnkTypes.each{ chunkLetter ->
(1..10).each{ streamNumber ->
String readParamName = readParamPrefix + '_' + chunkLetter + '_' + streamNumber
log.info('Read param name: ' + readParamName)
String writeParamName = writeParamPrefix + '_' + newBlobCounter
log.info('Write param name: ' + writeParamName)
String blob_id_to_delete = props.get(readParamName).toString().trim()
log.info('' + readParamName + ' => ' + writeParamName + ' (' + blob_id_to_delete + ')')
vars.put(writeParamName.toString(), blob_id_to_delete.toString())
newBlobCounter++
}
}
The script doesn't work for JMeter variables, but works fine for JMeter properties. Here is how JMeter properies look like:
JMeterProperties:
...
blob_to_delete_1=9b1c4f40-3e36-11e8-a5b4-3906549016d8
blob_to_delete_10=9da5e050-3e36-11e8-bac3-e51250ffea15
blob_to_delete_11=9b235420-3e36-11e8-bac3-e51250ffea15
blob_to_delete_50=9b656630-3e36-11e8-bac3-e51250ffea15
Could you tell me, how I can fix my code for setting up JMeter variables correctly?
I don't see any problem with your code:
So I would recommend:
Checking jmeter.log file for any suspicious entries
Checking what variables are defined using Debug Sampler and View Results Tree listener combination. See How to Debug your Apache JMeter Script article for more information on getting to the bottom of JMeter script failure or unexpected behavior.
Don't use ${varName} in scripts, Notice JSR223 Best Practices:
ensure the script does not use any variable using ${varName} as caching would take only first value of ${varName}. Instead use :
vars.get("varName")
You can also pass them as Parameters to the script and use them this way.
After you change it, look for errors in logs if it still doesn't works

can not pass variable to sampler's assertion in Jmeter - Groovy

I try to make a test that read from DB and assert the data
I create a JDBC request and JSR223 sampler + Jsr223 assertion.
in the sampler I created a variable called sensativity_results.
and I want to pass it to the assertion.
I used
vars.putObject("sensativity_results", sensativity_results);
and then in the assertion I try to call it and print it,
the problem is that Jmeter just not recognized the assertion,
Moreover I created another sampler called test to print the results of "sensativity_results" and Jmeter just pass it and not even execute it
int actual_sensativity ()
{
float Actual_sensativity;
int loop_num = vars.get("Loop_Number") as int;
int conversion_sense = vars.get("Conv_sens") as int;
int actual_conversion = vars.get("Conv_numbers_1") as int;
Actual_sensativity = (float) (actual_conversion/loop_num)*100;
System.out.println("************** Actual_sensativity in %: " + Actual_sensativity);
System.out.println("**conversion_sensativity: " + conversion_sense);
System.out.println("**actual_conversion: " + actual_conversion);
System.out.println("**loop number: " + loop_num);
return Actual_sensativity;
}
int sensativity_results;
sensativity_results = actual_sensativity();
vars.putObject("sensativity_results", sensativity_results);
System.out.println("sensativity_results: " + sensativity_results);
the test plan ran as expected until this step and stopped without any error it print the sensitivity results at the first sampler, and just not move on, can someone please advise?
Just put vars.put("sensativity_results", sensativity_results);
and it solved the issue
Assuming you will be using this sensativity_results variable as a String later on I would suggest storing it like:
vars.put("sensativity_results", String.valueOf(sensativity_results))
Otherwise you will get ClassCastException: java.lang.Integer cannot be cast to java.lang.String error on attempt to use it like ${sensativity_results}
Alternative way of accessing non-String variables would be using __groovy() function (available since JMeter 3.1) like:
${__groovy(String.valueOf(vars.getObject('foo')),)}

Calculating sha1 in Node.js returns different result than in PHP

I'm calculating SHA1 using the following PHP code:
$hash = base64_encode(sha1($password.$key, true).$key);
But when I do this in Node.js, it does not give me the same result:
var hash = crypto.createHash('sha1').update(password + key).digest('base64');
Why are the results different?
In your PHP code, you're appending the key to the sha1 before passing it to base64:
sha1($password.$key, true).$key
In order to replicate that in Node.js, you'll need to do the same:
var hash = crypto.createHash('sha1').update(password + key).digest('hex');
var result = new Buffer(hash + key).toString('base64');
Edit: after looking at the PHP docs on sha1, it looks like the second parameter being passed to sha1 is going to return non-hex data:
If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number.
So in order for the two snippets to function the same, you'd also need to modify the PHP to not pass that parameter:
$hash = base64_encode(sha1($password.$key).$key);
You need to append key in the nodejs:
// php
$hash = base64_encode(sha1($password.$key, true).$key);
// see this ^^^^
// node
var hash = crypto.createHash('sha1').update(password + key).digest('base64') + key;
// add this ^^^^^^

Resources