I am new to groovy.I am reading values for 2 variables from console with below lines of code.
System.in.withReader {
println "Version: "
version = it.readLine()
println "Doc Type:"
Doc=it.readLine()
call getBillID(version,Doc)
}
getBillid method is as below,
def getBillID(int version,int doc)
{
allNodes.BillID.each {
theregularExpression=/\d+_\d+_\d+_\d_\d+_\d+_\d_${version}_${Doc}_\d+_\d+/
if(it != "" && it =~ theregularExpression) {
println "******" + it
}
}
}
now i want to use those variable values in my getBILLID method but i am getting error as
No signature of method: ReadXML.getBillID() is applicable for argument types: (java.lang.String, java.lang.String) values: [9, ]
where i went wrong.can any one tell me plz..
In addition to #Kalarani's answer, you could also do this:
System.in.withReader {
print "Version: "
int version = it.readLine() as int
print "Doc Type: "
int doc = it.readLine() as int
getBillID( version, doc )
}
As an aside; I would be careful with your capitalisation and variable names, ie: you have a variable called Doc with a capital letter. This is not the standard naming scheme, and you are best using all lowercase for variable names. You can see where it has got confused in the getBillID method. The parameter is called doc (all lowercase), but in the regular expression you reference ${Doc} (uppercase again).
This sort of thing is going to end up causing you a world of pain and bugs that might take you longer to find
Where is the getBillId() method defined? and what is the signature of the method? It would help understanding your problem if you could post that.
Related
Have a need to change the value from String to Long in BeanShell Assertion to do verification.
First Apporach
long balance_after_credit = Long.parseLong(String.valueOf("${balance_after_credit_from_db}"));
Second Approach
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
For instance, consider am getting a value as '743432545' for the variable balance_after_credit_from_db.
Error
org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``long token_balance_after_credit = Long.parseLong(vars.get("token_balance_after_c . . . '' : Typed variable declaration : Method Invocation Long.parseLong
Weird thing is sometimes, I didn't get errors and the script is getting passed.
Can anyone please point out where am doing a mistake. TIA.
Inlining JMeter variables into code-based scripts is not something recommended so go for 2nd approach.
How do you know that exactly String is being returned from the database all the time? It easily can be any other object type, in fact any of described in the Mapping SQL and Java Types article. The way more safe approach will be something like:
if (vars.getObject("balance_after_credit_from_db") instanceof String) {
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
}
else {
log.error("Unexpected \balance_after_credit_from_db\" variable type");
log.error("Expected: String, Actual: " + vars.getObject("balance_after_credit_from_db").getClass().getName());
throw new Exception("Unexpected variable type");
}
So in case of non-String JDBC query result you will be able to see the relevant message in jmeter.log file
See Debugging JDBC Sampler Results in JMeter article for more information on working with the entities coming from databases in JMeter tests
The second option
long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
should work, provided you have a valid numeric variable value. For instance try to run something like this:
vars.put("x", "743432545");
long balance_after_credit = Long.parseLong(vars.get("x"));
It won't return any exception.
The problem is when the variable is not defined, has empty or non-numeric value. Then Long.parseLong will throw a NumberFormatException, which you shold catch and make use of (treat it as assertion failure):
String rawValue = vars.get("balance_after_credit_from_db");
long balance_after_credit = Long.MAX_VALUE; // initialize with some unrealistic value
try {
balance_after_credit = Long.parseLong(rawValue);
}
catch(NumberFormatException e) {
Failure = true;
FailureMessage = "Variable does not contain a valid long. It was " + rawValue + " instead";
}
I'm trying this thing for a while but can't figure out what am I doing wrong.
Here is sample function (which is similar to the original one, except for the hash, which is generated dynamically in the original one):
module Puppet::Parser::Functions
newfunction(:am_running_oss, :type => :rvalue ) do |args|
oss = {:linux=>["Slackware", "RedHat", "Caldera"],
:mac=>["Jaguar", "Lion", "Tiger", "Kodiak"],
:win=>["Chicago", "Daytona", "Longhorn"]}
cls = args[0]
if oss.key?(cls)
return oss[cls][0]
else
return 'undefined'
end
end
end
and then in my manifest, I have this:
$h= am_running_oss($::am_os_type)
notify { "=*=*= amRunningOS <|:|> ${h} =*=*=*=*=*=*=*=": }
(am_os_type is a fact, that returns win, mac or linux based on the node type)
I was expecting to see Jaguar or Slackware as the return value but I get undefined instead. Does anyone know what am I doing wrong? Is there anything still am I missing in terms of passing the args to the function? Cheers!!
Replying to my own question, in case google lands someone here looking for the same. The thing worked for me is to is define cls like this:
cls = args[0].to_sym if args[0].is_a? String
Cheers!!
I'm working on a shell for my project. I want the Shell class to override all print functions while the shell is running, so I've done this:
# WARNING: Blocks until the user exits.
def start
# Override Kernel print functions.
master_print = Kernel.method :print
master_puts = Kernel.method :puts
Kernel.module_exec {
define_method(:print) { |text = ""|
self.send(:print_override, master_print, text)
}
define_method(:puts) { |text = ""|
self.send(:puts_override, master_puts, text)
}
define_method(:puts_padded) { |text = ""|
self.send(:puts_override, master_puts, "")
self.send(:puts_override, master_puts, text)
self.send(:puts_override, master_puts, "")
}
}
# Readline loop and command parsing here...
end
This works well as long as only the Shell class is outputting any text, but as soon as a command class tries to puts I get this:
NoMethodError: undefined method `puts_override' for #<AddressKit::CLI::Interactiv
e::Commands::LoadTable:0x000000027735b0>
I thought that the print and puts blocks I wrote above would stay in this scope, not execute in which ever scope they happened to be called from. Is it possible to fix that?
Bonus question: How do I put the original print functions back? I had planned this:
Kernel.module_exec {
define_method(:print, &master_print)
define_method(:puts, &master_puts)
undef_method(:puts_padded)
}
But I haven't tried it yet, and I don't know if that will leave Kernel exactly as I found it.
While blocks do preserve scope, self is special and refers to the instance running the method (I assume because this is more useful).
An alternative strategy would be to use the fact that Kernel#puts just does $stdout.puts, so instead of overriding puts, set $stdout to one of your classes, that can massage the values before passing them to puts on the former $stdout.
When you're done, restore $stdout to its original value.
Well, I think I fixed the problem, but I'm not sure why it works. I'm guessing that the blocks are in both the scope where it was called from, as well as in the scope they were defined in, but with higher priority on the former. That would mean that I can't use self and expect it to point to the shell. Instead I did this:
shell = self
Kernel.module_exec {
define_method(:print) { |text = ""|
shell.send(:print_override, master_print, text)
}
define_method(:puts) { |text = ""|
shell.send(:puts_override, master_puts, text)
}
define_method(:puts_padded) { |text = ""|
shell.send(:puts_override, master_puts, "")
shell.send(:puts_override, master_puts, text)
shell.send(:puts_override, master_puts, "")
}
}
Which works perfectly but (if I'm right) would break as soon as the variable shell exists in the same scope as print or puts is called from. But it doesn't break, I tested it! I really have no idea what's going on and I'd be very grateful if somebody could explain it :-)
So here is my problem.
I want to retrieve a string stored in a model and at runtime change a part of it using a variable from the rails application. Here is an example:
I have a Message model, which I use to store several unique messages. So different users have the same message, but I want to be able to show their name in the middle of the message, e.g.,
"Hi #{user.name}, ...."
I tried to store exactly that in the database but it gets escaped before showing in the view or gets interpolated when storing in the database, via the rails console.
Thanks in advance.
I don't see a reason to define custom string helper functions. Ruby offers very nice formatting approaches, e.g.:
"Hello %s" % ['world']
or
"Hello %{subject}" % { subject: 'world' }
Both examples return "Hello world".
If you want
"Hi #{user.name}, ...."
in your database, use single quotes or escape the # with a backslash to keep Ruby from interpolating the #{} stuff right away:
s = 'Hi #{user.name}, ....'
s = "Hi \#{user.name}, ...."
Then, later when you want to do the interpolation you could, if you were daring or trusted yourself, use eval:
s = pull_the_string_from_the_database
msg = eval '"' + s + '"'
Note that you'll have to turn s into a double quoted string in order for the eval to work. This will work but it isn't the nicest approach and leaves you open to all sorts of strange and confusing errors; it should be okay as long as you (or other trusted people) are writing the strings.
I think you'd be better off with a simple micro-templating system, even something as simple as this:
def fill_in(template, data)
template.gsub(/\{\{(\w+)\}\}/) { data[$1.to_sym] }
end
#...
fill_in('Hi {{user_name}}, ....', :user_name => 'Pancakes')
You could use whatever delimiters you wanted of course, I went with {{...}} because I've been using Mustache.js and Handlebars.js lately. This naive implementation has issues (no in-template formatting options, no delimiter escaping, ...) but it might be enough. If your templates get more complicated then maybe String#% or ERB might work better.
one way I can think of doing this is to have templates stored for example:
"hi name"
then have a function in models that just replaces the template tags (name) with the passed arguments.
It can also be User who logged in.
Because this new function will be a part of model, you can use it like just another field of model from anywhere in rails, including the html.erb file.
Hope that helps, let me know if you need more description.
Adding another possible solution using Procs:
#String can be stored in the database
string = "->(user){ 'Hello ' + user.name}"
proc = eval(string)
proc.call(User.find(1)) #=> "Hello Bob"
gsub is very powerful in Ruby.
It takes a hash as a second argument so you can supply it with a whitelist of keys to replace like that:
template = <<~STR
Hello %{user_email}!
You have %{user_voices_count} votes!
Greetings from the system
STR
template.gsub(/%{.*?}/, {
"%{user_email}" => 'schmijos#example.com',
"%{user_voices_count}" => 5,
"%{release_distributable_total}" => 131,
"%{entitlement_value}" => 2,
})
Compared to ERB it's secure. And it doesn't complain about single % and unused or inexistent keys like string interpolation with %(sprintf) does.
I was reading a blog post and saw a groovy snippet that looked lik
while ( entry = inputStream.nextEntry ) {
// do something
}
In the while loop, is this groovy syntax that will cause the loop to break when entry is null?
Yes, but it will probably make the compiler complain about
a possible accidental assignment. A better practise is:
while ((entry = inputStream.nextEntry )!=null) {}
First week using Groovy and wanted to test this out. Thought I would share the test & results. Thanks for pointing this out.
def list = ['one', 'two', null, 'four']
def it = list.iterator()
def i
while (i = it.next()) {
println i
}
Result: one
two