ERR value is not an integer or out of range - lua

I have this code in a lua script which I run from .net.
const string script = " if redis.call('EXISTS', '{0}') == 1 then" +
" local user = redis.call('get','{0}')" +
" local value = cjson.decode(user)" +
" value['UserPreferences'] = cjson.decode('{1}')" +
" value['Timestamp'] = cjson.decode('{2}')" +
" local val=cjson.encode(value)" +
" redis.call('set', '{0}', val)" +
" redis.call('EXPIRE', '{0}','{3}')" +
" end";
var redisScript = string.Format(script, "User_" + userId, JsonConvert.SerializeObject(userPreferences), JsonConvert.SerializeObject(DateTime.UtcNow), ConfigurationManager.AppSettings["RedisKeyExpiryTime"]);
await Cache.ScriptEvaluateAsync(redisScript);
This returns the error :
Error: ERR value is not an integer or out of range
please give some feedback to solve the issue.

Related

print method in lua script/redis is not working

I am trying to execute the following script and getting the below error. Redis is running in docker
Exception in thread "main" org.redisson.client.RedisException: ERR
user_script:1: Script attempted to access nonexistent global variable
'print' script: 6f736423f082e141036b833d1f86b5a36a494611, on
#user_script:1..
I get the same error when I execute using redis CLI
127.0.0.1:6379> eval "print("Comparison is_made b/w minimum_value out of two is: ")" 0 (error) ERR user_script:1: Script attempted to
access nonexistent global variable 'print' script:
8598b7f0db450c711d3a9e73a296e331bd1ef945, on #user_script:1.
127.0.0.1:6379>
Java code. I am using Redison lib to connect to Redis and execute script.
String script = "local rate = redis.call('hget', KEYS[1], 'rate');"
+ "local interval = redis.call('hget', KEYS[1], 'interval');"
+ "local type = redis.call('hget', KEYS[1], 'type');"
+ "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"
+ "local valueName = KEYS[2];"
+ "local permitsName = KEYS[4];"
+ "if type == '1' then "
+ "valueName = KEYS[3];"
+ "permitsName = KEYS[5];"
+ "end;"
+"print(\"rate\"..rate) ;"
+"print(\"interval\"..interval) ;"
+"print(\"type\"..type); "
+ "assert(tonumber(rate) >= tonumber(ARGV[1]), 'Requested permits amount could not exceed defined rate'); "
+ "local currentValue = redis.call('get', valueName); "
+ "local res;"
+ "if currentValue ~= false then "
+ "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "local released = 0; "
+ "for i, v in ipairs(expiredValues) do "
+ "local random, permits = struct.unpack('Bc0I', v);"
+ "released = released + permits;"
+ "end; "
+ "if released > 0 then "
+ "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "if tonumber(currentValue) + released > tonumber(rate) then "
+ "currentValue = tonumber(rate) - redis.call('zcard', permitsName); "
+ "else "
+ "currentValue = tonumber(currentValue) + released; "
+ "end; "
+ "redis.call('set', valueName, currentValue);"
+ "end;"
+ "if tonumber(currentValue) < tonumber(ARGV[1]) then "
+ "local firstValue = redis.call('zrange', permitsName, 0, 0, 'withscores'); "
+ "res = 3 + interval - (tonumber(ARGV[2]) - tonumber(firstValue[2]));"
+ "else "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end; "
+ "else "
+ "redis.call('set', valueName, rate); "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end;"
+ "local ttl = redis.call('pttl', KEYS[1]); "
+ "if ttl > 0 then "
+ "redis.call('pexpire', valueName, ttl); "
+ "redis.call('pexpire', permitsName, ttl); "
+ "end; "
+ "return res;";
RedissonClient client = null;
try {
client = Redisson.create();
client.getRateLimiter("user1:endpoint1").setRate(
RateType.PER_CLIENT, 5, 1, RateIntervalUnit.SECONDS);
String sha1 = client.getScript().scriptLoad(script);
List<Object> keys =
Arrays.asList("user1:endpoint1", "{user1:endpoint1}:value",
"{user1:endpoint1}:value:febbb04d-6365-4cb8-b32b-8d90800cd4e6",
"{user1:endpoint1}:permits", "{user1:endpoint1}:permits:febbb04d-6365-4cb8-b32b-8d90800cd4e6");
byte[] random = new byte[8];
ThreadLocalRandom.current().nextBytes(random);
Object args[] = {1, System.currentTimeMillis(), random};
boolean res = client.getScript().evalSha(READ_WRITE, sha1, RScript.ReturnType.BOOLEAN, keys, 1,
System.currentTimeMillis(), random);
System.out.println(res);
}finally {
if(client != null && !client.isShutdown()){
client.shutdown();
}
}
checked the Lua print on the same line thread but io.write also is giving same error.
As in the comments wrote return() seems* the only way.
Example for redis-cli (set redis DB and use it in Lua)
(Collect Data and return as one string)
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. " | " end return(txt)'
Now the eval
eval "local f = redis.call('GET', KEYS[1]) return(loadstring(f))()" 1 LuaV
...shows whats in table: redis
(One long String no \n possible)
Exception: eval 'redis.log(2, _VERSION)' 0 gives out without ending the script but only on the server.
Than \n will work when you do...
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. "\n" end return(txt)'
...and the eval
eval 'local f = redis.call("GET", KEYS[1]) f = loadstring(f)() redis.log(2, f)' 1 LuaV

Cannot resolve method error when trying to reproduce the code

I know it's been a while since this issue was resolved ( Simple calculator in java - using boolean to ask if user wants to continue ), but I wanted to recreate this, and when I tried to run it, I got error for all mathematical operators (add, minus, multiply or divide). Error says: "Cannot resolve method 'add'/'minus'/'multiply'/'divide'"
Maybe it would be easier if I add the actual code:
import javax.swing.JOptionPane;
public class Calculator {
public static void main(String[] args) {
double numberOne;
double numberTwo;
double result;
String number1;
String number2;
String input;
boolean useCalculator = false;
while (!useCalculator) {
number1 = JOptionPane.showInputDialog(null, "This is a calculator\nEnter first number");
numberOne = Double.parseDouble(number1);
input = JOptionPane.showInputDialog(null, "Choose from the following options:\n+\n-\n*\n/");
while (input == null || !(input.equals("+") || input.equals("*") || input.equals("/") || input.equals("-")))
input = JOptionPane.showInputDialog(null, "Thank you! What would you like to do?\nPlease choose from the following options:\n+\n-\n*\n/");
{
input = JOptionPane.showInputDialog(null, "The operator" + input + "is invalid. Please choose a correct one");
}
number2 = JOptionPane.showInputDialog(null, "Enter second number");
numberTwo = Double.parseDouble(number2);
if (input != null && input.equals("+")) {
add(numberOne, numberTwo);
result = add(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("-")) {
minus(numberOne, numberTwo);
result = minus(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("*")) {
multiply(numberOne, numberTwo);
result = multiply(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("/")) {
divide(numberOne, numberTwo);
result = divide(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
}
}
System.out.println("End of program.");
}
}
Any thoughts on how to fix this and run it without those errors?
Thanks in advance :)
It looks like GUI was running in the background, so when I minimized window, I was able to see the calculator and to run it normally.
Message that was displayed in console was reminder about old JDK, so everything is fine now.

Extract REST API request json value to variable in RestAssured

We have to validate the value sent in our REST API request payload with Response value, Tried the below and was able to get the JSON array printed. How to get the specific object inside the array of the request JSON body.
Request Payload :
{
"Testinfo":{
"abc":2,
"xyz":"2020-01-01"
},
"Details":{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws"
}
}
}
Code :
jsonObject = (JSONObject) JSONValue.parse(request);
JSONObject Testinfo = (JSONObject) jsonObject.get("Testinfo");
JSONObject Details = (JSONObject) jsonObject.get("Details");
System.err.println("Testinfo value in the request is: " + Testinfo);
System.err.println("Details value in the request is: " + Details);
Output :
{
"abc":2,
"xyz":"2020-01-01"
},
{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws",
}
How to get specific value such as "Details.eductation.test3"
Tried below
JSONArray jsonArray = (JSONArray) JSONValue.parse(request)
but getting an error as :
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to net.minidev.json.JSONArray
Please guide.
Use JSONPath
String json = "{\r\n" + " \"Testinfo\": {\r\n" + " \"abc\": 2,\r\n"
+ " \"xyz\": \"2020-01-01\"\r\n" + "\r\n" + "\r\n" + " },\r\n" + "\r\n" + " \"Details\": {\r\n"
+ " \"eductation\": {\r\n" + " \"test1\": 9,\r\n" + " \"test2\": 100,\r\n"
+ " \"test3\": 50\r\n" + " },\r\n" + " \"neweductiona\": {\r\n"
+ " \"test1\": \"value\",\r\n" + " \"test2\": \"Draws\",\r\n"
+ " \"test3\": 50\r\n" + "\r\n" + " }\r\n" + " }\r\n" + "}";
JsonPath js = new JsonPath(json);
System.out.println("Value is : "+js.getString("Details.eductation.test3"));
Output :
Value is : 50

QuickBooks Desktop Integration

I have a task to make a syncing service that can sync the sales records present in the Quick books point of sale into the local database.
How to integrate Quick books desktop point of sale and web application(c#) via web connector?
Code used :
public string sendRequestXML(string ticket, string strHCPResponse, string
strCompanyFileName,
string qbXMLCountry, int qbXMLMajorVers, int qbXMLMinorVers) {
if (Session["counter"] == null) {
Session["counter"] = 0;
}
string evLogTxt="WebMethod: sendRequestXML() has been called by
QBWebconnector" + "\r\n\r\n";
evLogTxt=evLogTxt+"Parameters received:\r\n";
evLogTxt=evLogTxt+"string ticket = " + ticket + "\r\n";
evLogTxt=evLogTxt+"string strHCPResponse = " + strHCPResponse +
"\r\n";
evLogTxt=evLogTxt+"string strCompanyFileName = " +
strCompanyFileName + "\r\n";
evLogTxt=evLogTxt+"string qbXMLCountry = " + qbXMLCountry + "\r\n";
evLogTxt=evLogTxt+"int qbXMLMajorVers = " +
qbXMLMajorVers.ToString() + "\r\n";
evLogTxt=evLogTxt+"int qbXMLMinorVers = " +
qbXMLMinorVers.ToString() + "\r\n";
evLogTxt=evLogTxt+"\r\n";
ArrayList req=buildRequest();
string request="";
int total = req.Count;
count=Convert.ToInt32(Session["counter"]);
if(count<total) {
request=req[count].ToString();
evLogTxt=evLogTxt+ "sending request no = " + (count+1) + "\r\n";
Session["counter"] = ((int) Session["counter"]) + 1;
}
else{
count=0;
Session["counter"]=0;
request="";
}
evLogTxt=evLogTxt+"\r\n";
evLogTxt=evLogTxt+"Return values: " + "\r\n";
evLogTxt=evLogTxt+"string request = " + request + "\r\n";
logEvent(evLogTxt);
return request;
}
It is creating log in the end, how will i fetch the data from the QBPOS?

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

Resources