Java Lexer and Parser - java

I am writing a new editor for java using Xtext.
I want parser to parse the main class and replace the method call by actual code.
e.g
Class Test {
public static void main(String[] args ){
System.out.println("Virag");
method();
}
public static method(){
System.out.println("Purnam");
}
}
After parsing I want to return a document like mentioned below.
Class Test {
public static void main(String[] args ){
System.out.println("Virag");
System.out.println("Purnam");
}
}
I achieved this in lexer and parser by return of method body instead of method.
But later in editor, text region gets changed and any edit performed in editor goes wrong.
Character positions in documents are going wrong.
How to fix this problem?

You probably want to use the Code Generation concept of Xtext to transform the source code of your DSL into a new artefact where the methods' body are inlined.

Related

java: using an array of objects across files

OK so, im very new to java and the solution is probably simple so please bear with me, but basically i'm trying to make a film database using an array of a movie class. i have 3 .java files: the tester, the database, and the movie class. my problem is i'm really not sure how to make my tester file recognize the movies array from the database file, and every solution ive found has just given me more errors.
tester:
public class DatabaseTester extends MovieDatabase{
public static void main(String[] args) {
System.out.println(MovieDatabase.movies[1].getTitle());
}
}
the database:
public class MovieDatabase {
public static Movie movies[] = new Movie[2];
public static void movieDb(String[]args){
movies[1].setTitle("Test Title");
}
}
^the movie class has a set title method. i'm not too sure about the database's code in particular but it was the only way i could find that didn't give me errors. i'll post the full movie class if necessary but it's quite long so... only if needed
the error i get if i try to getTitle(); from the MovieDatabase:
Exception in thread "main" java.lang.NullPointerException
at DatabaseTester.main(DatabaseTester.java:35)
i'm aware this error is from the program thinking the array is not initialized, so it just must not be recognizing my database file... if i try to getTitle from the MovieDatabase, it simply doesn't recognize it, and will either give me an error or nothing. i cannot find a way to get around this aside from putting the Movie initialization in the main (which i have confirmed works, but it's not what i want to do).
You can try this the following changed code In the class DatabaseTester
public class DatabaseTester {
public static void main(String[] args) {
System.out.println(Database.movies[0].getTitle());
}
}

Java string declaration IntelliJ IDEA

Trying to declare a string in Java inside the main method of a Console application.
String s = "this is some text";
I get a red underline saying, 'class' or 'interface' expected.
If I change the code to read
String s = new String("this is some text");
everything works, or at least the code compiles. Using JDK 1.8 and have recently upgraded the IDE to version 2016.2.4.
This only occurs when declaring a new String, all other type declarations and initializations work without declaring a new instance, i.e.
int i = 0;
Anyone know why the first declaration won't work?
Similar behaviour is exhibited when trying to write to the console,
System.out.println("this is some text");
The word 'text' is red underlined saying 'class' or 'interface' expected.
EDIT: entire class as requested
package Sandbox;
public class Main {
public static void main(String[] args) {
System.out.println("this fails");
}
}
however
package Sandbox;
public class Main {
public static void main(String[] args) {
System.out.println(new String("this works"));
}
}
See screenshot below of actual code in the IDE. Comments welcome.
Looks like an issue with Language Injections in IntelliJ.
https://www.jetbrains.com/help/idea/2016.2/using-language-injections.html
Disable the Language Injections. That should fix your Problem.
An similiar issue with the println method and string is described here and has been solved by unregistering println from string injections: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206836685-System-out-println-hello-analyze-error

How to make a link betweeen the name a function and the actual function in java

I am building a user interface in netBeans (coding by hand, more flexible) with multiple toolbars.
What I am trying to do is create an actionListener for each button. I am retrieving names of the functions from XML and parse them to string. I will write implementations for those functions in a separate class, but my problem is the following:
How do I make the link between the function name and the string containing it's name?
Example: String is Open(), function will be Open(someParameter) and in the definitions class there will be static void Open(param).
First of all, consider my comment about your idea of dynamic button behavior resolved from strings being a wrong approach. However if you still need exactly what you asked, what you need is Reflection API.
Here's an example:
Class c = SomeClassWithMethods.class;
Method m = c.getMethod("someMethodName", String.class, Integer.class, Integer.TYPE);
m.invoke(baseObjectFromWhichToCallTheMethod, "stringParam", 10, 5);
Added:
Another option, which is a little bit prettier than reflection, but still a messy design, would be to use a map to link those Strings to methods. The code is a bit longer, but from the Java perspective it is much better than using reflection for your task (unless you have some specific requirement of which I'm not aware). This is how it would work:
//Interface whose instances will bind strings to methods
interface ButtonClickHandler {
void onClick();
}
class SomeClassYouNeed {
//One of the methods that will be bound to "onButtonOneClick()"
public void onButtonOneClick() {
log.info("ButtonOneClick method is called");
}
public void onButtonTwoClick() {
log.info("ButtonTwoClick method is called");
}
//Map that will hold your links
private static Map<String, ButtonClickHandler> buttonActionMap;
//Static constructor to initialize the map
static {
buttonActionMap = new Map<String, ButtonClickHandler>();
buttonActionMap.put("onButtonOneClick()",new ButtonClickHandler() {
#Override
public void onClick() {
onButtonOneClick();
}
});
buttonActionMap.put("onButtonTwoClick()",new ButtonClickHandler() {
#Override
public void onClick() {
onButtonTwoClick();
}
});
}
public void callByName(String methodName) {
final ButtonClickHandler handler = buttonActionMap.get(methodName);
if (handler == null) {
throw new IllegalArgumentException("No handler found by name: "+methodName);
}
handler.onClick();
}
}
After you call callByName("onButtonTwoClick()") it will fetch the respective instance of ButtonClickHandler which will use the static method onButtonTwoClick() to process the click of the button.
It seems to me that you are looking for the equivalent of JS "eval" function in Java. This might help. Nevertheless it is generally not a good idea as #Max stated, you might want to rethink your design.
If i have understood your question correctly you are trying to generate your code files based on some strings taken from a XML file. I can suggest you this library to generate your codes.
For tutorials you can visit this link.
You may even use the Java Reflection API. Here is a link for the tutorial.
Its upto you, that which of the above two you use.

Java translator for println usages to convenient logger

I often see (and reuse) 3rd party source code that doesn't have appropriate output. Is there any tool (code translator) that convert println output to suitable log framework code
private void processCreateTraining() {
System.out.println("Training set created");
//..
}
to something like
private void processCreateTraining() {
LOG.info("Training set created");
//..
}
It could be done by search-and-replace or Structural Replace in IDEA. But is there more sophisticated/robust solution that provide more flexibility: different logging framework support, ask severity on occurrence replace, string concatenation via StringBuilder.
If I come across third party libraries that use println all over the place, I tend NOT to use it. It is a sign of poor workmanship, and that implies (to me) that there are likely to be other more insidious problems with the code.
But no, I'm not aware of any plugin or tool to deal specifically with this case.
Sure, try something like this:
public static void main(String[] args) {
WrappedOutputStream los = new WrappedOutputStream();
System.setOut(new PrintStream(los, true));
System.out.println("catch me");
}
WrappedOutputStream.java
class WrappedOutputStream extends ByteArrayOutputStream {
public void flush() throws IOException {
String str = "WRAPPED: " + this.toString();
// process
}
}

Parser as main file?

I am trying to write a big system that inputs data from a text file, and has a parser file. So, do I have to write a main file that would call the parser, and if so, how would I call the parser file, just code it like this?
Parser parser = new Parser();
If not, what would be my options???? Thank you for your help :)
FOR the parser how would I specify the text file to be read on the command line. I have a
public static void main (String[] commandLineArgs)
how would I write a specific text file in this statement???? Would i replace the commandLineArgs? I forgot about this.
YourClass YourFile; // Need to fully qualified class name and full path for the file.
EDIT : If I understand correctly, you need something like this :
public class Parser {
public void parseFile (String file) {
// parsing code goes here.
}
public static void main (String[] commandLineArgs) {
Parser parser = new Parser();
parser.parseFile(commandLineArgs[0]); //
}
}

Categories