Jeval EvaluationException: Invalid use of quotes - single-quotes

When I try to evaluate an expression I get this error: net.sourceforge.jeval.EvaluationException: Invalid use of quotes.
To be clearer. I read my rules from a .txt files where after I put them in a hasmap.
I have tried:
#{mentor} = Chung
#{mentor} = "Chung"
#{mentor} == "Chung"
#{mentor} == 'Chung'
but still gives another error or same error.
What am I doing wrong?
List<String> approvalMentors = new ArrayList<>();
Evaluator evaluator = new Evaluator();
evaluator.putVariable("mentor", String.valueOf(graduationApprovalRequest.getMentor()));
for (HashMap.Entry<String, String> entry : this.schoolRules.entrySet()) {
try {
if(evaluator.evaluate(entry.getValue()).equals("1.0")){
approvalMentors.add(entry.getKey());
}
} catch (EvaluationException ex) {
Logger.getLogger(SchoolRules.class.getName()).log(Level.SEVERE, null, ex);
}
}
return approvalMentors;
.txt File I read my rules from
#{mentor} = 'Chung'

JEval internal validation logic assumes each "operand" (a part of the conditional expression) should be either a built-in function, a number, a special symbol, OR a quoted string. If there is even a single SPACE between the == and double-quote symbols, the check for correctness of quoted string fails. Each such operand should either begin AND end with a quote(s), or do not have the quote(s) at all. The latter is the case with numbers, for example.

Related

passing var-args to MessageFormat.format in kotlin

I am trying to parse errorCode like
4011=Error thrown expected: {0} found: {1}.
using Message.format in kotlin
loggingService.logTheMsg("4011", arrayOf("${expectedVal}", "${actualVal}"))
In logTheMsg I am using this code :
var errorMessage = props.getProperty(errorCode)
errorMessage = MessageFormat.format(errorMessage as String, args)
println("${errorMessage}.")
but getting output as :
Error thrown expected:[Ljava.lang.String;#38f3b4ba found: {1}.
It might help in answering , the same thing is achieved in java like this:
parse(value, new String[]{"firstName","lastName"});
And in parse:
parse(String value, String[]args) {
value = MessageFormat.format((String) value, args);
System.out.println(value);
}
prints:
my name is firstName lastName
To remove ambiguity, Kotlin requires 'spread operator' (*) on array which is going to be passed as vararg, i. e.
loggingService.logTheMsg("4011", *arrayOf("${expectedVal}", "${actualVal}"))
Also, "${expectedVal}" should be replaced with expectedVal:
loggingService.logTheMsg("4011", *arrayOf(expectedVal, actualVal))
And, of course, you can use varargs as they intended to be used:
loggingService.logTheMsg("4011", expectedVal, actualVal)

Else without If error... and I don't know why

The code below is action taken when a button is clicked on a simple form. The problem comes with the one if/else block. The If line is not terminated. The Else line is not terminated. But I have a consistent error that my Else exists without an If. I can't see why. I need someone smarter than me to identify what is going on here.
Thank you in advance!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
FileFilter filter;
filter = new FileNameExtensionFilter("Comma Separated Value files","csv","txt");
JFileChooser chooser;
chooser = new JFileChooser();
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int showDialog = chooser.showDialog(this, null);
File selectedFile = chooser.getSelectedFile();
String filename;
filename = selectedFile.getAbsolutePath();
if (filter.accept(selectedFile))
{
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
else
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
}
You are missing the bracket '}' after "jTextField2.setBackground(Color.white);" and else.code is here
if (filter.accept(selectedFile))
{
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
}
else
{
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
The SYNTAX for if-else Block looks like this:-
if {
// statements
} else {
//statements
}
Now if you are having only ONE statement inside the if Or else part then you can afford to skip the curly braces{ } otherwise you surely need to put those curly braces as compiler looks for it can terminate the execution of if statement.
However, it is always recommended to use the braces even if u have only ONE statement inside the if or else part as it improves the readability of the code.
You need to close your "if" and "else" blocks.
Example: if {} else {}.
if (filter.accept(selectedFile)) {
jTextField2.setText(filename);
jTextField2.setBackground(Color.white);
} else {
jTextField2.setText("You Did NOT Select a CSV File.");
jTextField2.setForeground(Color.black);
jTextField2.setBackground(Color.red);
}
The if's closing bracket is missing just before the else.

NHibernate Criteria Filtering

I use this code to filter database records
if (!string.IsNullOrEmpty(_searchCriteria.MessageType))
{
var messageType = (AutotransferMessageType)Enum.Parse(typeof(AutotransferMessageType), _searchCriteria.MessageType, true);
if (Enum.IsDefined(typeof(AutotransferMessageType), messageType))
{
criteriaQuery.CreateAlias("AutotransferInputRecord", "AutotransferInputRecord")
.Add(
Restrictions.Eq(
"AutotransferInputRecord." + AutotransferLogSearchCriteria.MessageTypePropertyName,
messageType));
}
else
{
criteriaQuery.Add(Restrictions.IsNull("AutotransferInputRecord"));
}
}
AutotransferMessageType is enumerable type
public enum AutotransferMessageType
{
[DisplayName("MT202")]
[DatabaseName("MT202")]
MT202,
[DisplayName("MT210")]
[DatabaseName("MT210")]
MT210,
//...
}
My filter outputs the results when I enter MT202, for example. (It's the right behavior).
When I input just number, for example, 202, I get no results (It's the right behavior too).
But when I try to input some line, "mt", for example, I get error
Unexpected application error has been occured:
'Requested value 'mt' was not found.'
How to make the filter do not show any results when I input a line?
Your error is coming from the line that parses the enum. Use Enum.TryParse instead:
AutotransferMessageType msgEnum;
var enumPrasedOk = Enum.TryParse(_searchCriteria.MessageType, true, out msgEnum);
if(enumPrasedOk){
//Do something
}else{
//Handle case where enum was not found for some reason (if need be)
}
Also please note that you can not look up the enum this way using it's description (in your case they are the same so it is ok).

Powershell and SQL parameters. If empty string, pass DBNull

I got this parameter:
$objDbCmd.Parameters.Add("#telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value?
I tried:
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };
But that gives me the error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."
And if I convert it to a string, it inserts an empty string "", and not DBNull.
How can this be accomplished?
Thanks.
In PowerShell, you can treat null/empty strings as a boolean.
$x = $null
if ($x) { 'this wont print' }
$x = ""
if ($x) { 'this wont print' }
$x = "blah"
if ($x) { 'this will' }
So.... having said that you can do:
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
But I'd much rather wrap this up in a function like:
function CatchNull([String]$x) {
if ($x) { $x } else { [DBNull]::Value }
}
I don't know about powershell, but in C# I would do something like this:
if ([string]::IsNullOrEmpty($objUser.Telephone))
{
$objDbCmd.Parameters["#telephone"].Value = [DBNull]::Value;
}
else
{
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
}
Always append +"" at the end of db values...
$command.Parameters["#EmployeeType"].Value= $ADResult.EmployeeType + ""
Many years later, let me clarify:
Josh's answer shows a helpful simplification for testing strings for emptiness (relying on PowerShell's implicit to-Boolean conversion[1]), but it is unrelated to Tommy's (the OP's) problem.
Instead, the error message
"Failed to convert parameter value from a ResultPropertyValueCollection to a String."
implies that it is the non-null case that caused the problem, because $objDbCmd.Parameters["#telephone"].Value expects either a string value or [DBNull]::Value, whereas $objUser.Telephone is of type [ResultPropertyValueCollection], i.e. a collection of values.
Thus, in the non-null case, a string value must be assigned, which must be derived from the collection; one option is to take the first collection element's value, another would be to join all values with a separator to form a single string, using, e.g., [string]::Join(';', $objUser.Telephone) or, if joining the elements with spaces is acceptable (not a good idea with multiple phone numbers), simply with "$($objUser.Telephone)".[2]
Detecting an empty collection via [string]:IsNullOrEmpty() actually worked, despite the type mismatch, due to how PowerShell implicitly stringifies collections when passing a value to a [string] typed method parameter.[2]
Similarly, using implicit to-Boolean conversion works as expected with collections too: an empty collection evaluates to $false, a non-empty one to $true (as long as there are either at least two elements or the only element by itself would be considered $true[1])
Therefore, one solution is to use the first telephone number entry:
$objDbCmd.Parameters["#telephone"].Value = if ($objUser.Telephone) {
$objUser.Telephone[0].ToString() # use first entry
} else {
[DBNull]::Value
}
Note: If $objUser.Telephone[0] directly returns a [string], you can omit the .ToString() call.
In PowerShell v7+ you can alternatively shorten the statement via a ternary conditional:
$objDbCmd.Parameters["#telephone"].Value =
$objUser.Telephone ? $objUser.Telephone[0].ToString() : [DBNull]::Value
[1] For a comprehensive summary of PowerShell's automatic to-Boolean conversions, see the bottom section of this answer.
[2] When implicitly converting a collection to a string, PowerShell joins the stringified elements of a collection with a single space as the separator by default; you can override the separator with the automatic $OFS variable, but that is rarely done in practice; e.g., array 'foo', 'bar' is converted to 'foo bar'; note that this conversion does not apply when you call the collection's .ToString() method explicitly, but it does apply inside expandable (interpolating) strings, e.g., "$array".

getting user defined error messages using antlr3

numberrange returns [String value]
: numberrangesub
{
String numberRange = ($numberrangesub.text);
String [] v = numberRange.split(",");
if ( Integer.parseInt(v[0].trim()) < Integer.parseInt(v[1].trim())) $value =numberRange;
else throw new RecognitionException();
}
;
Please observe the above ANTLR code. In this I want to throw a user friendly error message like "from value should be less than to value in BETWEEN clause".
I am expecting like this RecognitionException("from value should be less than to value in BETWEEN clause"); But antlr did not accept like as above.
In java class where I am calling the generated java class by Antlr. I am handling like as follows.
try
{
parser.numberRangeCheck();
}
catch (RecognitionException e)
{
throw createException("Invalid Business logic syntax at " + parser.getErrorHeader(e) + ", " + parser.getErrorMessage(e, null), Level.INFO, logger);
}
Any help will be appriciated.
Why not simply throw a RuntimeException with your custom error message?
// ...
else throw new RuntimeException("from value should be less than to value in BETWEEN clause");
// ...
As Terrance wrote in "The Definitive ANTLR Reference" error chapter excerpt:
To avoid forcing English-only error messages and to generally make
things as flexible as possible, the recognizer does not create exception
objects with string messages. Instead, it tracks the information necessary to generate an error.
So there is no error message supplied to RecognitionError's constructor. But you can define additional field of your recognizer to hold user-friendly error message shown on RecognitionError handling:
numberrange returns [String value]
: numberrangesub
{
String numberRange = ($numberrangesub.text);
String [] v = numberRange.split(",");
if ( Integer.parseInt(v[0].trim()) < Integer.parseInt(v[1].trim()))
$value = numberRange;
else {
this.errorMessage = "from value should be less than to value in BETWEEN clause";
throw new RecognitionException(this.input);
}
}
;
And then override the getErrorMessage method:
public String getErrorMessage(RecognitionException e, String[] tokenNames) {
String msg = this.errorMessage;
// ...
}
This works similar to paraphrase mechanism explained in the same excerpt.