jFlex methods (yypushStream,yypopStream..) trigger "cannot find symbol" error in user code - jflex

I have some user code in jFlex that generates a BufferedReader from yytext(), then has it pushed into the stream stack.
However, it seems that yypushStream(), yypopStream(), yymoreStreams() methods are not recognized by javac and trigger a "cannot find symbol" error whenever those methods are called from within the user code.
For instance:
public void toStream(String a){
InputStream fstream= new ByteArrayInputStream(a.getBytes());
BufferedReader freader = new BufferedReader(new InputStreamReader(fstream));
yypushStream(freader);
}
Returns the following output:
symbol: method yypushStream(BufferedReader)
Yylex.java:389: error: cannot find symbol
yypushStream(freader);
^
I've also tried Yylex.yyPopStream(); and %public to no effect.
Is it that those methos cannot be used in the user code?
Thanks

If you read carefully Jflex Manual, it is written that the methods yyPushStream(), yyPopStream() and yyMoreStreams() are available only in the skeleton file called skeleton.nested, that you find in the src folder.
So you shouldn't use it or call it in the user code.

Related

Nwjs how to use evalNWBinModule in another created window?

In the main window I write the following code and it works:
nw.Window.get(null).evalNWBinModule(null, "./my.bin", "./my.js");
import("./my.js");
but if I create a new window via nw.Window.open(MyOtherURL); where I then move this code, then after running I get an error:
Uncaught (in promise) TypeError: Failed to resolve module specifier
'./my.js'
what is the launch difference and what else do i need to configure?
nw.Window.get() returns a reference to the Window itself, so you can then chain off of it.
nw.Window.open(), does not, but it does have a callback function gives you access to the new window, which you can chain off of.
const url = 'page2.html';
const options = {};
nw.Window.open(url, options, function (win) {
win.evalNWBinModule(null, './my.bin', './my.js');
});
However I'm not sure that will do what you want. You will likely be better off having the code run in your page2.html file directly.

displaying a different line of code in an eclipse editor (without changing everything else)

Setting: I am doing a programming experiment where I need to display a different method signature (one line of code) to my test persons than the line of code actually exists. Example:
// this code should be visible
public def aFunction(def a, def b) {
// this line of code should be used
public void aFunction(String a, List<String> b) {
The intention is that everything works like when the source code included the second line (like code completion, errors etc.), but only the first line is visible.
I've already tried patching the groovy editor I use and replacing some text on load and on save, but that just does not seem to do the job, using some code like
IDocument doc =this.getDocumentProvider().getDocument(this.getEditorInput());
doc.set(doc.get().replaceAll(...));
Sadly this leads to strange behavior like always marked as dirty files.
I've also tried using the getCompilationUnit method that the groovy editor supplies, but somehow this does not help in any ways (maybe because the "wrong" code was still visible in the editor?).
Finally I tried to wrap the InputStream for the IFile underlying the IEditorInput in the doSetInput-method like
IFile resource = (IFile) input.getAdapter(IFile.class);
InputStream in = resource.getContents();
//...wrap stream
resource.setContents(in, false, true, null);
but this only leads to the editor being completely empty.
Anyone got an idea on how to solve that problem?

Changing working directory in Scala [duplicate]

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.
I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.
I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....
There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.
The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant OpenJDK bug was closed in 2008 as "will not fix".
If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jnr-posix. Here's the maven info
As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.
See Runtime.exec javadocs
Specifically,
public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException
where dir is the working directory to run the subprocess in
If I understand correctly, a Java program starts with a copy of the current environment variables. Any changes via System.setProperty(String, String) are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...
The working directory is a operating system feature (set when the process starts).
Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:
File f = new File ( System.getProperty("someprop"), myFilename)
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
I have tried to invoke
String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());
It seems to work. But
File myFile = new File("localpath.ext");
InputStream openit = new FileInputStream(myFile);
throws a FileNotFoundException though
myFile.getAbsolutePath()
shows the correct path.
I have read this. I think the problem is:
Java knows the current directory with the new setting.
But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.
The solution may be:
File myFile = new File(System.getPropety("user.dir"), "localpath.ext");
It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.
~~~~JcHartmut
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
You can change the process's actual working directory using JNI or JNA.
With JNI, you can use native functions to set the directory. The POSIX method is chdir(). On Windows, you can use SetCurrentDirectory().
With JNA, you can wrap the native functions in Java binders.
For Windows:
private static interface MyKernel32 extends Library {
public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);
/** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
int SetCurrentDirectoryW(char[] pathName);
}
For POSIX systems:
private interface MyCLibrary extends Library {
MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);
/** int chdir(const char *path); */
int chdir( String path );
}
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);

How to retrieve IProblem instances from current editor?

I'm writing an Eclipse plugin, and I'd like to retrieve all instances of IProblem associated with the currently open text editor. I've tried the following:
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IEditorPart editor = window.getActivePage().getActiveEditor();
if (!(editor instanceof AbstractTextEditor)) {
return null;
}
ITextEditor textEditor = (ITextEditor)editor;
IDocumentProvider docProv = textEditor.getDocumentProvider();
IDocument doc = docProv.getDocument(editor.getEditorInput());
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(doc.get().toCharArray());
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
return cu.getProblems();
However, when I run it against the following code in the editor:
import java.io.Serializable;
public class TestClass implements Serializable {
/**
*
*/
}
It doesn't find any problems. I would expect it at least finds a MissingSerialVersion problem. Perhaps I'm parsing the file incorrectly, which might cause this issue. I feel like there should be a way to get the CompilationUnit from the editor directly?
Update:
If I add a syntax error to the source file and then invoke the plugin, it reports the syntax problem, but not the missing serial version UID. I suspect this is some kind of configuration issue where warnings aren't being reported.
2nd Update:
This isn't just restricted to the MissingSerialVersion problem. Anything that is a warning, and not an error, is not found by this method. If I change the problem that I want to see to an error in the compiler settings (or even by passing in additional options to the parser making it an error instead of a warning), I still get no joy from the getProblems() method with respect to warnings. (It shows actual errors just fine, e.g. if I put an unrecognized symbol in my source code).

Getting STDIN in eclipse?

I need to write a code for competition using STDIN and STDOUT, how can I set up eclipse to take input from STDIN??
When I was just using editor and command line I was running:
java Hatch < hatch_input
Now I need the equivalent to work directly from eclipse. It would be perfect if I could use it directly from file, but it would to suffice to just be able to paste the actual input somewhere, as long as I can write code that takes STDIN directly in eclipse by clicking RUN.
class Main{
public static void main (String[] args) throws java.lang.Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
}
Above code is what I am trying to achieve.
When you run your program you can setup a run configuration. Just click on on the arrow next to the play button and choose "Run configurations..."
In the new run configuration dialog you create a new Java application run configuration. In the tab "Arguments" you can enter the arguments you want the program to receive.
Suggestion: In the last tab, "common", choose to save it as a shared file, this will create a *.launch file that you can use to quickly run the program. You can also create different launch files for different inputs.
You can also just type in the input data or copy paste in the console window of the eclipse. for Sdtin when the program hits that point focus shifts to console and waits for the response.
There is following code,which i tried. this code is working fine if you run program in command prompt, but in eclipse not working because there console are no longer waiting for user input and give the java.lang.NullPointerException.
if you are read data by user input you can use System.in.read(). and this is also working in eclipse console.
In this code you can get Data from user but this data is not args which we throw at run time...
public class CONSOLE
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Console c = System.console();
System.out.println("Enter Username : \t");
String u = c.readLine();
System.out.println("Enter Password : \t");
char[] p = c.readPassword();
System.out.println("USERNAME : "+u);
System.out.println("PASSWORD : "+String.valueOf(p));
}
}
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();