Solved

Convert string into Java statement to execute.

Posted on 1997-10-17
15
555 Views
Last Modified: 2009-07-29
I'd like to know how I can convert string
containing Java statement into real Java
statement which can be executed?
Suppose I have some file which has following
condition string in prefixed format:
 
---
# file contents
condition:  "(a > b && a > c)"
...
---
 
Now In program,
 
---
{
    String strCond = "";

    // 1. Read the file and store "..."
    // part into String strCond;
    // 2. Now convert strCond into actual
    // Java statement somehow.

    // following should be equivalent to
    // if (a > b && a > c) to compiler            
    if (strCond) {
        do_something();
    }
}
---
 
Thanks.
0
Comment
Question by:dongwon
15 Comments
 

Author Comment

by:dongwon
ID: 1229035
Edited text of question
0
 
LVL 4

Expert Comment

by:rembo
ID: 1229036


There is no simple way to do this.  You'll need to
either parse things out using the StringTokenizer()
some kind of grammar.  

Another way would be to parse out the condition section,
then wrap things into a file:

System.out.println("if " + condition + " { \n\tdo_something();\n}");

when you save that to a file, you could compile into
a package and then load the package on the fly.  

That's about it, there's no simple way do self-modifying
code.  


0
 

Author Comment

by:dongwon
ID: 1229037
Thanks for your answer.

I guess this is more difficult problem than I expected.

First way that you suggested is not good. Since the syntax of
condition part in file (condition : "here") accepts whole
Java syntax, if I have to manipulate StreamTokenizer() or some other lex/yacc tools, then I end up writing whole Java parser.

For second suggestion, I'm not sure what you mean by that exactly. Probably little elaboration would be appreciated.

Thanks.
0
 

Author Comment

by:dongwon
ID: 1229038
Adjusted points to 150
0
 

Author Comment

by:dongwon
ID: 1229039
Adjusted points to 200
0
 
LVL 4

Expert Comment

by:rembo
ID: 1229040

If the piece after the "condition: " is always a
Java condition, then you still need to either parse
it out or write it out to a file, compile it and
then load the class to use.  

The with the first thing, if it's always a java condition
statement, you can do a subString() to eliminate the
first 11 characters so:

String newStr = conditionStr.subString(11, conditionStr.length - 1);

then, you just have to parse conditions out with the
StringTokenizer.  If, as you said, they are just Java
test statements, you just need to be able to parse out
the different comparisons and balance parens.  

Hope that helps,

-Tony

0
 

Author Comment

by:dongwon
ID: 1229041

In file, after condition, any "legal" java statement can come, not only testing statement. For instance, following can happen.

condition1: "(a > b && a > c)"
condition2: "System.out.println("..."); System.exit(0);"
condition3: "String s = tmp.subString(0, 10); while (true) doTest(s);"
...

In code

{
      if (condition1) {
            condition2;
      } else {
            condition3;
      }
}

I guess as you said there is no easy to do this...

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 4

Expert Comment

by:rembo
ID: 1229042

Let's try a different approach.  How is this file
getting created?  Java may not be the best solution
to this problem.  We may be able to convert this file
into Java using a Perl script.  Then you can compile
the file (we can put that in the perl script too.

If that's acceptable, send me a copy of a file, and
I'll send you a script that will convert it.

-Tony



0
 
LVL 4

Expert Comment

by:rembo
ID: 1229043

Oh, my e-mail is rembo@cks.com

-Tony

0
 

Author Comment

by:dongwon
ID: 1229044

First of all, I should appreciate for your help and patience.
 
Now let me explain the situation where I need those functionalities.
 

Let's suppose I have 2 systems A and B (which are distributed and
geographically remotly located). Both systems model same domain and even have exactly same data under different schema.  For instance, following is the schema:

---
(NOTE I'm calling this as "Meta Information")

A: name(string), day(int), month(int), year(int), type(int)
B: title(string), type(string), date(string - mm/dd/yy format)
---

My goal is that when system A gets a query conforming to its schema, A should translate the incoming query into another query conforming to the schema of system B and pass it on the system B.

Note that there are several obstacles:      
 
1. mismatched name with same semantic attribute (A.name <->    
   B.title)
2. mismatched type with same semantic attribute
   (A.type(int) <-> B.type(string))
3. 1 to n mapping (A.date <-> composite of
   (B.day,B.month,B.year))

For instance, following QA should be translated into QB.

QA:     select name
        from A
        where day = 31 and month = 12 and year = 97 and
        type = 145
 
QB:     select title
        from B
        where date = '12/31/97' and type = 'type-145'

Another important requirements is that above "Meta Information" should not be hard-coded into system A or B. That is, those information should be written in some file and loaded into the system.

Hence, I'm thinking following file along with its ad-hoc grammar to express such translation mechanism.
 
---
# syntax       LHS:       RHS

# translation from A to B.
A.name:             sprintf(B.title, "%s", $1);
A.day,A.month,A.year:       sprintf(B.date, "%d/%d/%d", $2,$1,$3);
A.type:                  sprintf(B.type, "type-%d", $1);

# translation from A to C
...


Example is shown using C syntax. The meaning should be clear: LHS (for instance, A.name) will be translated using RHS function where built-in variables $1, $2, ... are to be bound to the value of variables in LHS. (for instance, in second line, $1 = A.day, $2 = A.month, $3 = A.year).

Here comes the problem. After the system loads in above file and
parse it, it should RUN the RHS part (sprintf() part) to do
translation. By modifying the above file (that is, meta information), user is able to change the translation, without touching the actual system. In some sense, the system's translation mechanism is dumb since it simply run the parsed RHS part in run-time.

This is why I asked if I could convert string into java statement (I decided Java for implementation). If you see better way for this problem (without using conversion from string to statement...), that's fine. If you use Perl to achieve same effect, that's fine too.

I hope I explained well the essence of the problem to you.

Thanks.
                                     

0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1229045
Only as an alternative suggestion you and rembo might want to consider:

If you can define a set of all possible conditionals, for instance:

(a > b && a > c)
(a < b && a > c)
(a < b && a < c)


Than you can define a simple parser that determines which conditional structure was invoked and call a diffrent method for each case.

This would work arround all kinds of problems like forcing the client code to have access to a Java compiler, generating byte code manualy and class signature violations.


0
 
LVL 4

Expert Comment

by:russgold
ID: 1229046
You have described a system which requires parsing of some grammatical construct (your example is SQL), and translation according some dynamically defined meta-data. This is not conceptually too bad; however, it is not quite as easy as you had hoped in Java, since Java does not give you an easy way to compile strings.

You have a few options:
1. Use a language such as LISP, which does support compilation of strings dynamically (of course, you have to use LISP grammar, which can be a bit off-putting).

2. Use a tool like JavaCC <http://www.suntest.com/JavaCC/>, which simplifies the creation of grammars in Java. It should be at least as easy to use as yacc.

3. Define a very simple grammar, and write an ad-hoc parser.

It sounds as though the real guts of your program is the meta-data, not the parsing, so I would advise solution 2 to make it as simple as possible.  A JavaCC newsgroup is in the process if being voted, and there is already a mailing list to offer detailed help on it.
0
 
LVL 4

Expert Comment

by:rembo
ID: 1229047


Is it set up so that the first statement is the
test, the second statement is what happens if
it's true, the second if it's false?  

If so, I'll give you a script to do it.

-Tony

0
 

Author Comment

by:dongwon
ID: 1229048
Thanks for the tip, but my question was for more general one.
In fact, current approach is using JavaCC tool to specify ad hoc
language and my intention was to avoid this scheme.
0
 

Accepted Solution

by:
Threshold earned 200 total points
ID: 1229049
If you run it in Application, not Applet, there is one way...

1. get java statement file, ie:  mycode.java
2. use Runtime.exec("javac mycode.java") to compiler it
3. use Class.forName("...mycode") to get the instance of your class
4. call the method of your class

0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Receive file in Servlet 1 36
count11 challenge 6 48
micro services vs rest web services 16 53
Java passing arguments (type error) 2 35
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now