Retrieving ERROR messages from SWI-Prolog using Java

When executing prolog programs from java (either using the terminal or JPL) it is important to be able to find out if the prolog program has problems. Such programs may be uploaded by users, as in the case of Gorgias Cloud.

To get the output you need to execute your prolog file from the java runtime. Use the snippet below to get a demo:


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.";
      Process p = Runtime.getRuntime()
          .exec("\"Path to swipl.exe, e.g. C:\\Program Files\\swipl\\bin\\swipl.exe\" -o /dev/null -c " + userProjectPath + userFilename);
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String line;
      while ((line = reader.readLine()) != null) {
    } catch (IOException e1) {
    } catch (InterruptedException e2) {

yum: duplicate packages problem

This problem is based on a yum update or yum install failed operation, due to a network error or failure. It happened to me while updating a Centos 7 system. During the update the network was disconnected and the update operation failed. Then after executing:

yum update

I had an error indicating that several packages had duplicates, e.g.:

rpm-4.11.3-25.el7.x86_64 is a duplicate with rpm-4.11.3-21.el7.x86_64

To cope with this problem you need to remove the new version -that was not correctly installed- from the rpm database, using the command:

rpm -e --justdb --nodeps rpm-4.11.3-25.el7.x86_64

You need to do this for all packages (above run for package rpm-4.11.3-25.el7.x86_64) marked as duplicates in the yum check command. Then, just do a normal update:

yum update

and the system will download the newest versions of all packages.

To resolve this issue I was helped by this thread @ centos forums

Complex Graphical Models using Eclipse GMF technology

Today I am going to discuss about two features of Eclipse GMF that are not well covered by the documentation and that are difficult to locate in forums. For this article I used the Eclipse Modeling Tools Mars 2 Package. After installing the package you must go to Help -> Install Modeling Components and select and install the Graphical Modeling Framework Tooling.

The first feature is to have text areas that can span multiple lines of text.

The second feature is to be able to print my model (as I may want to have it is xps or pdf format). By default GMF allows only for printing your models in png (picture) format.

I will take you step by step to these features definition using a simple example. Assume you have a newspaper and you want to publish articles. The page of the newspaper has one or more articles. Articles have a title, a teaser and text.

1. Create the project and the metamodel

You first need to create a new Modeling project. File-> New-> Project..->Ecore Modeling Project (see the next figure).


Now define the model as a collection of pages, and the pages are collections of articles.  To do that right click on the newspaper.ecore file and click on “Initialize ecore_diagram diagram file”. Use the aggregation (or composition if you use the aird file) relationship from the toolbox and click and drag from the Newspaper EClass to the Page EClass and for Page to Article. Define the relationships and properties shown in the following diagram.


It is interesting to take a look at the properties of the aggregation. Right click on the line of the articles relationship and select the properties view (see figure below). To indicate that the articles can be from one to many you assign to the property “Lower Bound” the value 1 and to the “Upper Bound” the value -1.


Now assume that you want the teaser and text properties of the Article to be able to have multiple lines of text (the first deature we discuss in this article). In order to do that you need first to open the genmodel file. Then you will select the teaser attribute and you set its “Property Multi-line” to the value true. By default it is false, so make sure to do that.


Finally select the top level node in the genmodel diagram and check its properties. Set the Compliance Level to 6.0 (if you do not do this then when building the gmfgen file you will get an error):


Now you are ready to initialize the code for editing the model’s elements. Right click on the Newspaper element of the genmodel and select “Generate All”. This will create the ecore Model Code in this project and generate the Edit Code project that you need.


2. Generating the Graphical Model

Now you are ready to start working with GMF. Open the GMF Dashboard. Select Window->Show View->Other and type GMF and immediately you will see the GMF Dashboard appear. Select it and you will see it in your eclipse window.


The first task is to select the ecore (Domain Model) and genmodel (Domain Gen Model) files:


Next you derive the gmfgraph model by clicking Derive from the Domain Model towards the Graphical Def Model. I named it newspaper1.gmfgraph (see first figure below, in your machine you can give it the name newspaper.gmfgraph, I cannot because I already have one graph file). Then I selected the newspaper element in the Next step of the dialog (see second figure below), and in the final step of the dialog (see third figure) I selected that I want graphical representations for the Page (with the number attribute) and Article (with all its attributes, i.e., name, teaser and text).




Now if everything is OK you can see the following newspaper1.gmfgraph file on eclipse:


All elements are in the Canvas. The Canvas has a Figure Gallery (we will see it in detail later), the Node elements that refer to the objects that will be displayed and the Diagram Label elements that refer to the text boxes that will display attributes (bottom part of the figure). Now, in the Figure Gallery we have two main Figure Descriptors, one for the Page (PageFigure) and one for the Article (ArticleFigure). Each of these has a Rectangle with the default Flow Layout and as many Child Access elements as its text boxes (attributes). Note that this is not enough, there are also the relevant Labels defined in the Rectangle. The Diagram Label elements refer to the Child Access elements and the latter refer to the Label elements. In the Label element you can add children like Insets (to space the text from the limits of the rectangle) and  a Basic Font to define text size and style – regular, bold or italics:


Now we need to define a new Rectangle in Page where we will be inserting Article objects. Right click on the Rectangle PageFigure and select New Child -> Rectangle:


Name the Rectangle element PageCompartmentFigure. See its properties:


Now you need to add a Border Layout Data child to the PageCompartmentFigure and add to the Rectangle PageFigure a Child Access element with properties:


Now go to Canvas -> New Child -> Compartment, name it PageCompartment with the following properties:


Save it and for now you are finished with the gmfgraph file. The next step is to go to the GMF Dashboard and Derive the gmftool model. First you select its name, then you select the newspaper element and finally, the two objects that you are going to be using to draw the model, i.e. the Page and the Article. See these three steps of the wizard:




Now you are ready to Combine all these models (using again the GMF Dashboard) to get the gmfmap model. Follow again the steps of the wizard. Take care to remove Article from the Links compartment in the fifth step. It must look as in the fifth figure below:






Then you have to take care of the Nodes Page and Article because they need a final touch. Select Article and then click the button Change. Add the first EReference articles to the Children Feature:



Now you have to edit the newspaper.gmfmap file. It is shown below. See that it contains the ecore, gmfgraph and gmftool models. We are going to focus on the gmfmap part. The Mapping has two elements of type Top Node Reference (one for articles and one for nodes) and a Canvas Mapping. Verify that the

Each Top Node Reference has a Node Mapping. The Node Mapping of Article has a Feature Label Mapping whose properties are displayed in the figure below:


Now you have to add the Feature Label Mapping that are missing with similar properties. Note that the one for Page (number) is not of type EString but of type EInt. I have its properties shown below:


The final part in mapping is to add the compartment of the page.Right click to Node Mapping <Page/Page> -> New Child -> Child Reference and then again right  click to Node Mapping <Page/Page> -> New Child -> Compartment Mapping. You do not have to type anything in their properties, just select the right items. See both their properties in the figures below:



Now save it, if all has gone well you are ready to press transform from the gmfmap model to the gmfgen model in GMF Dashboard. You finished the process:


Insert Printing Capability

Double click the newspaper.gmfgen file to open it. Now you click its Gen Editor Generator top element. Its properties Diagram File Extention and Domain File Extention show the extentions of the files related to newspaper. The models will have the extention .mewspaper and the graphical models .newspaper_diagram. See also all the files in the models folder of our projet on the left:


Now select the Gen Plugin Newspaper Plugin element and set its property Printing Enabled to true:


Now your models will have the printing capability! Now save and right click on the newspaper.gmfgen file and select to generate the diagram code:


Add Text Multi-line capability

Normally the Newspaper.diagram project has been created successfully and you can see it in the following figure. It is ready to work with it. However, we want the teaser and the text elements of the articles to be able to span multiple lines of text. To achieve that you need to edit a number (six actually) java files in package The first two files that you need to edit are the and You need to find their createContents() method. Initially it is like in the figure:


You need to locate the lines where the fFigureArticleTeaserFigure.setText(“<…>”) method is called and add the code:


Do the same for the fFigureArticleTextFigure. Do not forget to set the method to not be automatically generated from now on (generated NOT). You must do that because if for any reason  – e.g. you want to change the fonts of the labels – you re-generate the diagram code you will lose your changes. See the final outcome in the following figure:


You have to repeat the above process for file

Now you get the,,, and make another change. Take for example the first of them, i.e.,, and locate its getManager() method:


Now you have to locate the line with code:

setManager(new TextDirectEditManager(this, null, NewspaperEditPartFactory.getTextCellEditorLocator(this)));

and replace null with WrapTextCellEditor.class. This classhas not been imported yet, so hover your mouse over it and select to import


Then remember to add generated NOT and save it:


Do not worry about the deprecated warning, it is just a warning 🙂

Now you have to do the same for the other three files. After that you are ready to test your model! To do that right click on your Newspaper.diagram project and select Run as -> Eclipse Application.

Create my first newspaper

Create a new project and name it MyNewspaper. Then right click on the project and select New -> Example -> Newspaper Diagram

Let it have the default name and add pages and then articles. To add an element click on it at the palette on the right hand side of the following figure. Then if it is a Page click anywhere in the canvas to insert a page. If it is an Article click inside a page to insert it there. Then add your text:


Now do you want to print your model? Just right click on the canvas and select File -> Print:



Υπολογισμός ακρότατων συνάρτησης δύο μεταβλητών

Όταν θέλω να υπολογίσω τα ακρότατα μιας συνάρτησης δύο μεταβλητών χρειάζεται να κάνω κάποιους υπολογισμούς. Παρακάτω, μια έτοιμη συνάρτηση για το Matlab και το Octave για τον υπολογισμό των ακρότατων και την 3D γραφική παράσταση που τα παρουσιάζει. Ο κώδικας για να δουλέψει χρειάζεται το συμβολικό πακέτο (symbolic package), το οποίο δεν περιλαμβάνεται στις τυπικές εκδόσεις των matlab (symbolic math toolbox) και octave (octsympy).

Εάν θέλετε να μάθετε και τη θεωρία πίσω από τους υπολογισμούς σας παραπέμπω στις σημειώσεις του Καθ. Γεώργιου Ανδρουλάκη.

Λοιπόν έχουμε και λέμε, ο κώδικας είναι ο:

function akrotata(syn,pedia_timwn)
%Ypologizei akrotata synartisis syn me 2 metablhtes x, y. 
%H sinartisi f dinetai ws alfarithmitiko kai proairetika mporeite na dwsete ta pedia timwn gia ta x, y me th morfi [x_min,x_max, y_min, y_max] (metabliti pedia_timwn). 
%An den balete timh sta pedia_timwn tote sto grafima 0a deite tin syn otan ta x,y anikoyn sto [-pi,pi].
syms x y f;
if nargin < 2
    pedia_timwn = [-pi,pi,-pi,pi];
if size(a) > 0
    for i=1:size(a)
        vfxx=double(subs(subs(fxx,x,a(i)), y, b(i)));
        vfyy=double(subs(subs(fyy,x,a(i)), y, b(i)));
        vfxy=double(subs(subs(fxy,x,a(i)), y, b(i)));
        vfxx_times_vfyy = vfxx*vfyy;
        if vfxx < 0 && vfyy < 0 && vfxx_times_vfyy > vfxy2
            sprintf('\nYparxei topiko megisto sto shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
        elseif vfxx > 0 && vfyy > 0 && vfxx_times_vfyy > vfxy2
            sprintf('\nYparxei topiko elaxisto sto shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
        elseif vfxx_times_vfyy < vfxy2
            sprintf('\nSagmatiko  shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
    disp('Den yparxoun akrotata')

Πληκτρολογήστε ή επικολλήστε τον κώδικα σε ένα αρχείο akrotata.m , επιλέξτε τον φάκελο στον οποίο το έχετε αποθηκεύσει και για να το δοκιμάσετε εκτελέστε στο παράθυρο εντολών την παρακάτω εντολή:

>> akrotata('(x^2+4*y^2)*exp(1-x^2-y^2)',[-2,2,-2,2])

Η γραφική παράσταση φαίνεται στο παρακάτω σχήμα:


Ενώ η έξοδος της συνάρτησης φαίνεται στην εικόνα:



Debugging a Java application querying Prolog using Eclipse

You normally start a new eclispe java project, let’s name it TestPrologInterface (see Figure 1 below).

To use JPL you need to import the jar file in your project. You right-click on the project’s name and click on Properties (or from the Eclipse menu bar you select Project->Properties). Then on the Libraries tab you click on the Add External JARs… button and select the jpl.jar (see Figure 2 below).

Then, you can add a new class and paste in the code from my previous blog entry (see Figure 3 below).

Subsequently, you will need to setup a run configuration for executing/debugging your project. To do that you select on the Eclipse menu bar the Run->Run Configurations… option, then you right-click on Java application and select New. Then you add the names of the project and main class (see Figure 4 below).

The next thing to do is define the right environment variables. To do that you need a command prompt where you will execute the command:

  "c:\Program Files\swipl\bin\swipl.exe" --dump-runtime-variables=cmd

See the resulting environment variables in Figure 5 below.

Now you are ready to configure the variables on eclipse. In the run configuration go to the Environment tab and then add the variables one by one (click Add and insert the information from the previous screen, from each line the left hand side as name and the right hand side as value). You can see the results in Figure 6 below.

Finally, you run the configuration by clicking on Run (bottom right). The result is shown at the bottom of Figure 7, where you see the eclipse screenshot including the source code.

If you want to export the project to a runnable jar file you right click on the project name and select Export. In the dialog that opens you select Java->Runnable jar file. In the next dialog you define the name of the exported jar and don’t forget to check the Package required libraries into generated JAR if you want the jpl.jar file to be included (see a screenshot in Figure 8).

Now you are ready to distribute your application. Distribute it with the batch file that I used in my previous blog entry.

Figure 1: Create a new project dialog

Figure 2: Add the JPL JAR file to library

Figure 3: New class dialog

Figure 4: Create a new run configuration dialog

Figure 5: Using the command line to find the SWI-Prolog environment variables

Figure 6: The environment tab in the new run configuration dialog

Figure 7: The java class and the execution output

Figure 8: The runnable JAR export dialog

Querying Prolog from Java

This blog entry is for those who want to use Prolog queries from their Java program. I use swi-prolog, a free implementation of the Prolog language.

The SWI-prolog installation includes the java jpl7 package (in the lib installation folder):

To use it from java you need to setup some system variables before executing your app. Moreover, the java and swi-prolog installations must both be 32 bit or 64bit. For example you can edit a run.bat batch file with the following commands (assuming that swi-prolog is installed in c:/program files/swipl and your app is in the executable <your jar name>.jar file):

  set SWI_PROLOG_PATH=c:\program files\swipl
  set path=%path%;%SWI_PROLOG_PATH%\bin\;%SWI_PROLOG_PATH%\lib\
  swipl.exe --dump-runtime-variables=cmd > plvars.bat
  call plvars.bat
  java -jar <your jar name>.jar

This approach assumes that the jpl.jar library file is included in your jar file, otherwise you must add the jpl.jar to the classpath variable. In the next blog entry I explain how to do that using eclipse.

See an example that adds in the fact father(john,nikos) to the prolog database and then runs the query father(X,nikos):

import java.util.Map;
import org.jpl7.*;

public class TestPrologInterface {

  public static void main(String[] args) {
    String s = "assert(father(john,nikos)).";
    Query q = new Query(s);
    // run the query
    if (q.hasNext()) {
      // now I can ask for the father of nikos
      s = "father(X,nikos).";
      q = new Query(s);
      // run the query, repeat while there are more results
      while (q.hasNext()){
        //get a mapping of variables to instantiations:
	Map<String, Term> map =;
	//get the instance of variable X
	String varX = map.get("X").toString();
	//print variable instance