In Java I have a method:
private boolean testFunction(int x){
// codes goes here..
}
Now I have a expression written in file something like:
if(testFunction(10)){ return "ok"; }else{ return null;}
I am storing this in a String variable inside java program and want to execute it like it should execute as Java code:
if(testFunction(10)){ return "ok"; }else{ return null;}`
Is it possible?
The thing is I have a web application where there are 10+ different kind of form having different kind of fields i.e in some form X,Y,Z is there and X,Y is required....in some form A,B,C is there and C is only required like this.
So instead of writing validation code for each form i wanted to write a expression in XML file and at the time evaluation these expression will execute by single java method and return some value. So in this way I will just have to write expression in XML file.
No. Java is a compiled language, it is not interpreted.
There are ways of generating bytecode dynamically in Java, but they are highly involved, and aren't anywhere close to the concept of eval(String code)
If you want dynamic validation for form entries, I'd suggest using RegExp expressions which can be evaluated and matched against form input at runtime.
Unfortunately your OP was a bit vague as to what you're actually trying to achieve.
To get you started: RegExp Pattern class
Related
Given a string, how can I validate the contents are a valid PCRE within Java? I don't want to use the regex in any way within Java, just validate its contents.
java.util.regex.Pattern is almost good enough, but its javadoc points out how it differs from Perl.
In detail, there's a system with 3 relevant components:
Component A - Generates, among other things, Perl-compliant regular expressions (PCREs) to be evaluated at runtime by some other component capable of executing PCREs (component C). What's "generated" here may be coming from a human.
Component B - Validates that data generated by component A and, if valid, shuttles it over to the runtime (component C).
Component C - Some runtime that evaluates PCREs. This could be a Perl VM, a native process using the PCRE library, Boost.Regex, etc., or something else that can compile/execute a Perl-compliant regular expression.
Now, component B is implemented in Java. As mentioned above, it needs to validate a string potentially containing a PCRE, but does not need to execute it.
How could we do that?
One option would be something like:
public static boolean isValidPCRE(String str) {
try {
Pattern.compile(str);
} catch (PatternSyntaxException e) {
return false;
}
return true;
}
The problem is that java.util.regex.Pattern is designed to work with a regular expression syntax that is not exactly Perl-compliant. The javadoc makes that quite clear.
So, given a string, how can I validate the contents are a valid PCRE within Java?
Note: There are some differences between libPCRE and Perl, but they are pretty minor. To a certain degree, that is true of Java's syntax as well. However, the question still stands.
I'd want to insert a predefined string into my step definition in Cucumber using java. Here's what I have:
Java Code
public String temp = "hello";
//insert temp into my step:
#Then("^the "+temp+" should be empty$")
public void the_should_be_empty() throws Throwable {
//do things
}
But I keep getting this error:
"The value for annotation attribute Then.value must be a constant
expression"
So, how do I insert a string into my capturing step?
=============
More Info
I am trying to have a set list of "global keywords" used in many of my BDD step definitios. So when I add a new "global keyword", it will be changed in all my BDD. For example (red|yellow|green) could be used in 10 different BDD steps, and I want to add blue without changing all 10 steps. Instead I want a String variable that contains the list, then insert this variable into my BDD.
The short answer is: "You don't".
The longer is that the value in the annotation must be a constant. It cant be something that is constructed run time.
The way Cucumber matches steps between Java and scenarios is by using the regular expression you define in the annotation. The process fails if the value is constructed run time. The Cucumber runner will locate and use all the regular expressions found in the step implementations and then search the feature files to match code with scenario steps.
This is why you can't build the string to match against run time.
It would be interesting to understand why you want to build the string run time. What are you trying to achieve?
A consequence of creating many different strings is that there must be many different steps in your scenarios that should match. To me, it feels like you have misunderstood something. Please share what you are trying to achieve and maybe we can help you with another approach.
You can achieve this by using a custom parameter type.
Once defined, your step def will look like this:
#Then("the {color} should be empty")
public void the_should_be_empty(Color color) throws Throwable {
//do things
}
Now if the list of colors changes, you don't have to edit every stepdef.
I have a filtering application written in Java that will allow me to filter companies based on their fundamentals (e.g. pretax profit, dividend yield etc.).
I have created a filtering engine that, at the moment is hard-coded to take filters that have been given at compile time.
What I want to do is open up a web service where I can pass in JSON to run the filtering using filters defined and passed in at runtime.
To do this I need to somehow convert strings into Java code.
So for example the following string in JSON:
current.preTaxProfit > previous.preTaxProfit
into Java code like this:
return current.getPreTaxProfit() > previous.getPreTaxProfit();
The main issue I am having is parsing mathematical strings such as:
current.preTaxProfit > (previous.preTaxProfit * 1.10)
Things could get very complex very quickly, especially when it comes to inner brackets and such, and adhering to BODMAS.
Are there any libraries out there specifically for parsing mathematical strings, or does anyone know any good resources that could help me?
For example, I have found this:
Javaassist: http://davidwinterfeldt.blogspot.co.uk/2009/02/genearting-bytecode.html
Does anyone have any experience of using Javaassist? In my architecture I pass in objects ith 'callback' methods implemented, so the ability to create entire classes and methods could useful.
Two possibilities:
the Java Scripting API:
the EL, Expression Language.
The scripting API might be most fast to get results from, but EL is nicer.
Consider using of an expression language, for instance JEXL.
If you put current and previous into the context, just evaluate:
current.preTaxProfit > (previous.preTaxProfit * 1.10)
Complete example:
// create context
JexlContext jc = new MapContext();
context.set("current", someObject);
context.set("previous", anotherObject);
// create expression
String jexlExp = "current.preTaxProfit > (previous.preTaxProfit * 1.10)";
Expression e = jexl.createExpression(jexlExp);
// evaluate
Object result = e.evaluate(jc);
I often find myself searching for statements of a particular form in Java. Say I've written a simple function to express an idiom, such as "take this value, or a default value if it's null"
/** return a if not null, the default otherwise. */
public static <T> T notNull(T a, T def) {
if (a == null)
return def;
else
return a;
}
Now if I've written this, I want to look for cases in my code where it can be used to simplify, for instance
(some.longExpressionWhichMayBeNull() ? "default string" : some.longExpressionWhichMayBeNull())
The problem is that it's pretty tricky to write a regular expression that matches java syntax. It can be done, of course, but it's easy to get wrong. It's hard to get regular expressions to ignore whitespace in all the right locations always accurately figure out where strings start and stop, know the difference between a cast and a function call etc.
It also seems a bit wasteful, since we already have a java parser, which does that already.
So my question is: is there some Java syntax aware alternative to regular expressions for searching for particular (sub-)expressions?
You'd probably need to build an abstract syntax tree of the Java source file(s) and then analyse that. Might be possibly to leverage PMD (http://pmd.sourceforge.net/) and write a custom rule (http://pmd.sourceforge.net/pmd-5.0.5/howtowritearule.html) to detect and flag expressions that could be optimised as you describe.
I am getting a String into Java program from a user via command line arguments.
The question is what kind of checks I should perform to prevent possible attacks and vulnerabilities?
I am not expert in security area, but as far as I know
In C too long line specified by user and handled improperly could lead to buffer overflow
In PHP line containing ` characters and handled improperly could lead to SQL injection
For now I can not think about any specific format of a String to apply some regex to check. It can be arbitrary, but if is looks harmful I want to quit immediately. The string might to send to a Java server with network, there it might be used for an SQL query.
if (args.length > 0) {
String arg0 = args[0];
if (!isValidString(arg0)){
System.exit(1);
}
}
public boolean isValidString (String str) {
if (str == null) return false;
//TODO: many more checks here
return true;
}
I am sure Java is much more secure than C or early PHP, but what should I be aware about?
If this main class does nothing other than passing its argument to somewhere else, then it's not its responsibility to validate the string.
If this string finally goes to a class which uses it in a SQL query, then it's the responsibility of this class to use a prepared statement and thus make sure no SQL injection attack is possible.
If this string ends up being part of a generated HTML page, then it's the responsibility of the HTML generator to HTML-escape the string.
A string, by itself, is never harmful. If you have to validate it, then you need to know when it is valid, and when it's not. And it depends on the context.
It all depends on what you are doing with the string, as in what inputs you are expecting obviously always double check those before you use them.
If you are worried about SQL injection from users you can use prepared statements to help prevent against SQL Injection as the statement is compiled before it is used and the query plan stored for further use so the parameters do not become part of the executable SQL.
If you are worried about user input appearing on web pages etc then you should escape it for a webpage:
Recommended method for escaping HTML in Java
The escaping / validating you should do depends entirely on your use for the string.
I'm afraid, that this question is far-fetched problem.
In worst case, I think, (I can't imagine how it could be reproduced) you could have a deal with OutOfMemory exception if a String array passed into main() method will be enough large.