Search code examples
javaswi-prologjpl

Retrieving ERROR messages from SWI-Prolog using Java and JPL


When I use JPL (from JavaSE 1.8), Prolog (SWI-Prolog version 8.2.2) can return an error message without throwing an exception. E.g. when using consult and the file has errors:

import org.jpl7.Query;

public class Test {
  public static void main(String[] args) {
    try {
      String t1 = "consult('test.pl')";
      Query q1 = new Query(t1);
      q1.hasNext();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

I get the output at the console:

ERROR: test.pl:1:23: Syntax error: Unexpected end of file

But no exception is thrown. Therefore my Java program cannot know that the consulted file has errors. The file test.pl that I used in this simple example only contains a simple predicate with a syntactical error:

brother(mike, stella)..

What can I do so that my Java program can catch this error? A post with a similar title doesn't seem to resolve this issue...

Maybe I can use a syntactical checking method either from JPL, or another source, any concrete ideas?


Solution

  • It finally occurred to me to try to use the terminal to get the error or warning messages. I used the Java Runtime class to execute swipl.exe with the file in question as parameter. Needed a little processing of the output but it worked fine. The following block of code demonstrates the solution:

    import java.io.BufferedReader;
    import java.io.IOException;  
    import java.io.InputStreamReader;
    
    public class TestCMD {
    
        public static void main(String[] args) {
            try {
                String userProjectPath = "Path to the folder of your file, e.g. E:\\";
                String userFilename = "Your file name, e.g. test.pl";
                Process p = Runtime.getRuntime().exec("\"Path to swipl.exe, e.g. C:\\Program Files\\swipl\\bin\\swipl.exe\" -o /dev/null -c " + userProjectPath + userFilename);
                p.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }
        }
    }
    

    This solution is also given at my blog.