How to call karate feature file into karate-config.js file [duplicate] - javascript

I have an application that creates a token once by using karate.callSingle() in my karate-config file.
This token however expires after some time, so I might need to recreate it after some tests.
My plan would be to set the time of creation in a variable that can be shared in subsequent iterations of the karate-config file, so that I can recreate the token if the time difference is big enough.
Is there a way in Karate in which I can set a variable in the karate-config that can be shared in subsequent iterations ?

In the end I followed Peter Thomas' advice and used Java by "caching" properties between features. Here's my implementation :
var tokenRefreshTimeInMinutes = 5;
var myToken = {};
var KarateCache = Java.type('KarateCache');
var lastRefreshTime = KarateCache.get('lastRefreshTime');
if (!lastRefreshTime || differenceInMinutes(new Date(lastRefreshTime), new Date()) >= tokenRefreshTimeInMinutes) {
myToken = karate.call('theFileRefreshingTheToken');
KarateCache.add('lastRefreshTime', new Date().toUTCString());
KarateCache.add('myToken', JSON.stringify(myToken));
} else {
myToken = JSON.parse(KarateCache.get('myToken'));
}
with this simple KarateCache Java class
private static final Map<String, String> KARATE_CACHE = new ConcurrentHashMap<>();
public static void add(String key, String value) {
KARATE_CACHE.put(key, value);
}
public static String get(String key) {
return KARATE_CACHE.get(key);
}

Are you storing the result of callSingle() to a variable? Like:
var tokenResult = karate.callSingle('createToken.feature', config);
If you save the expiration time to a variable expirationTime inside createToken.feature, you can access it in karate-config.js as tokenResult.expirationTime.

Related

Calling script from Blazor with parameters

I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);

How to return data from cloud function to android and use it?

How can I get data from Cloud onCall() function to Android client and use it in a java code?
The client connects to function and function connects to firestore. But I can`t get data back from the function to client. I know that data has json format. But how to pass data to android, and how to use this data in android code (for example to setText in TextView).
java onClick() method:
onClick(){
String first = editTextTitle.getText().toString();
String second = editTextDescription.getText().toString();
//Here I try to setText received from function, but nothing happen.
tv_function.setText(function_3(first, second).toString());
}
java - call function:
private Task<String> function_3(String first, String second) {
mFunctions = FirebaseFunctions.getInstance();
Map<String, Object> data = new HashMap<>();
data.put("text", first);
data.put("push", second);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>()
{
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws
Exception {
String result = (String)task.getResult().getData();
return result;
}
});
}
javaScript function:
exports.sendMessageToAndroid = functions.https.onCall((data, context) => {
var batono = {
first: data.fara,
second: data.mina
}
return db.collection('abra-codabra').doc("mu-mu").set(batono)
.then(()=>{
var arba = {
aram:"aramando",
borem:"boremuno"
}
return arba;
});
});
How to get var "arba" to AndroidStudio and set it to TextView?
By doing
Map<String, Object> data = new HashMap<>();
data.put("text", first);
data.put("push", second);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
...
(as shown in the example from the documentation) you send to your Callable Cloud Function a map with a text element.
However, in your Cloud Function code you do:
var batono = {
first: data.fara,
second: data.mina
}
So, it means that you should send a map with the following elements: fara and mina, not a map with text (or you would have done something like var batono = {text: data.text}).
So, you should most probably do something like the following (not tested however):
Map<String, Object> data = new HashMap<>();
data.put("fara", .....);
data.put("mina", .....);
data.put("push", true);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
...

Why my GET call gets an array with empty objects?

I have a c# web project that has some REST request to do to get data from the db. My problem is: I have a GET call which return an array of the size of the number of rows returned by the query but every object is empty. While I'm debugging, every object has all the data I need but when the data reach the javascript the array is full of empty object. Where am I wrong?
This is the request on the .js file:
$.get("api/giacenzemobile/getGiacenze", function (data) {
console.log(data)
});
This is the function on the model file (.cs)
public static List<GiacenzeMobile> EstraiGiacenzeMobile()
{
List<GiacenzeMobile> giacenzeMobile = new List<GiacenzeMobile>();
SqlCommand cmd = null;
SqlConnection sqlconn = null;
using (sqlconn = new SqlConnection(Configurazione.ConnessioneDB))
{
sqlconn.Open();
string query = "...";
cmd = new SqlCommand(query, sqlconn);
SqlDataReader res = cmd.ExecuteReader();
while (res.Read())
{
GiacenzeMobile giac = new GiacenzeMobile();
giac.IdGiacenza = res.GetInt32(0);
//..... set all data ...
giacenzeMobile.Add(giac);
}
return giacenzeMobile;
}
}
And this is the controller (.cs):
public class GiacenzeMobileController : ApiController
{
[Route("api/giacenzemobile/getGiacenze")]
public IEnumerable<GiacenzeMobile> GetGiacenze()
{
return GiacenzeMobile.EstraiGiacenzeMobile();
}
//...other code...
}
And this is the result write on the console log:
Array(6)0: {}1: {}2: {}3: {}4: {}5: {}
SOLVED
I didn't set as public the fields of the GiacenzeMobile object.
If your attributes are private kotlin will not add it to the JsonString when it is deserialized. So make them public or remove the private identifier

Wicket AbstractDefaultAjaxBehavior do recursive update the page

I have some ajax Behaviour that should pick some data using JS, and turn it back to Java. Sometimes it works but quite ofen it is just add url parameter and do page refresing/
public abstract class LoggedVKIdBehaviour extends AbstractDefaultAjaxBehavior {
private static final Logger logger = LoggerFactory.getLogger(LoggedVKIdBehaviour.class);
#Override
protected void respond(AjaxRequestTarget target) {
String loggedVkId = RequestCycle.get().getRequest().getRequestParameters().getParameterValue("logged_vkid").toString();
logger.info("ajax has comming with logged VK ID " + loggedVkId);
recived(target, loggedVkId);
}
protected abstract void recived(AjaxRequestTarget target, String loggedVkId);
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
Map<String, Object> map = new HashMap<>();
map.put("callbackFunction", getCallbackFunction(CallbackParameter.explicit("logged_vkid")));
//
PackageTextTemplate ptt = new PackageTextTemplate(LoggedVKIdBehaviour.class, "vkid_callback.js");
OnDomReadyHeaderItem onDomReadyHeaderItem = OnDomReadyHeaderItem.forScript(ptt.asString(map));
response.render(onDomReadyHeaderItem);
}
}
js template
var calback = ${callbackFunction};
var logged_vk_id = 11;
function authInfo(response) {
if (response.session) {
logged_vk_id = response.session.mid;
calback(response.session.mid);
console.log("recived callback from VK " + logged_vk_id);
}
}
$(document).ready(function () {
VK.Auth.getLoginStatus(authInfo);
});
it is do recursive redirection like http://localhost:8080/mytool/product/1?logged_vkid=332797331&logged_vkid=332797331&logged_vkid=332797331&logged_vkid=332797331&logged_vkid=332773...
As i understand Ajaj technology - iti asynchronus requests, that shouldn't touch main url at all. So what is the reason for page refreshing?
this is generated Callback function
function (logged_vkid) {
var attrs = {"u":"../wicket/bookmarkable/com.tac.kulik.pages.product.ProductPage?12-1.IBehaviorListener.0-&productID=1"};
var params = [{"name":"logged_vkid","value":logged_vkid}];
attrs.ep = params.concat(attrs.ep || []);
Wicket.Ajax.ajax(attrs);
}
I use wicket 7.2
I did a lot investigations for few days. And found that when i remove
setPageManagerProvider(new NoSerializationPageManagerProvider(this));
Application throw me exepton in polite logs
org.apache.wicket.WicketRuntimeException: A problem occurred while
trying to collect debug information about not serializable object look
like it is could come from aused by: java.io.NotSerializableException:
com.tac.kulik.panel.smaccounts.SMAccountsPanel$1
which means that page tryed to be serialized for SOME REASON but $1 it is mean Anonimous class. I had few class created anonimously to ges some ajax links coming from ListView to be managed on parent panel. So After removing this Anonimous class logic, everything start and run well.
So i am happy, but still don't understand which reason page did serialization after ajax, and what the reason was to refresh whole page.

How to pass a const void * to node.js?

i'm extending the libspotify wrapper of node-libspotify to support album cover images.
so far, i have the following, working c-binding code:
static Handle<Value> Album_Cover(const Arguments& args) {
HandleScope scope;
// test arguments sanity
assert(args.Length() == 2);
assert(args[0]->IsObject()); // sp_session
assert(args[1]->IsObject()); // sp_album
ObjectHandle<sp_session> *session = ObjectHandle<sp_session>::Unwrap(args[0]);
ObjectHandle<sp_album> *album = ObjectHandle<sp_album>::Unwrap(args[1]);
const byte *image_id = sp_album_cover(album->pointer, SP_IMAGE_SIZE_LARGE);
size_t image_size;
const void *image_data;
if(image_id) {
sp_image *image = sp_image_create(session->pointer, image_id);
image_data = sp_image_data(image, &image_size);
sp_image_release(image);
}
return scope.Close(image_data);
}
i struggle on the last line: how can i pass the raw image data over to node.js when running scope.Close(...)?
thanks for any suggestsions.
You should wrap it in a v8::Value as v8::HandleScope::Close expects a handle to one as an argument.
I guess v8::String should do it - v8::String Class Reference
scope.Close(String::New((const char*)image_data, image_size));
A v8::Array might be useful too - it all depends on how you are going to use the returned value afterwards.
I hope this helps.

Categories