Sunday 4 November 2012

Jena tutorial - Reasoning with user defined rules

Hi,

This tutorial will provide you with Java code and jar libraries that you need to run a simple rule reasoning example using the Jena framework.

I used Eclipse, so my tutorial will be around its functionality. This tutorial will also assume that you know the basics of Eclipse and Java.

At the end of the tutorial you should have an Eclipse project looking like:



1) So, first create a Java project in Eclipse, name it whatever you want (I call it SWIFC) and create a package inside the project where you will create your main class (I call it com.oanaureche.swifc).

2) Second, create a folder in your Eclipse project and name it lib. In here you will put all the jar libraries needed to run the main class.

3) Download the jars that you will need for running the main class and copy or cut and paste them in the lib directory. The figure above shows what libraries you will need for running the tutorial's code.

4) Add the libraries to the project's Build path in Eclipse. I will skip the instructions on how to do this. There is plenty material on the internet that show you how to do this. It's not that complicated really.

5) Create two text files inside the project and a) Add the dataset (raw data, RDF data) to the dataset.txt file and b) write the rule in the rule.txt file

These are the contents of the dataset.txt file:


@prefix : <http://oanaureche.com/prefix#> .
@prefix pre: <http://jena.hpl.hp.com/prefix#> .
:Joseph pre:father :Mary .
:John pre:brother :Joseph .


These are the contents of the rule.txt file:


@prefix pre: <http://jena.hpl.hp.com/prefix#>.
[rule1: (?f pre:father ?a) (?u pre:brother ?f) -> (?u pre:uncle ?a)]

6) For your main class, create a class inside the package that you create in step 1 (I call it ReasonWithRules.java) . The contents of this file are:


package com.oanaureche.swifc;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.rulesys.Rule;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.rdf.model.Statement;
import java.net.MalformedURLException;

public class ReasonWithRules {

/**
* @param args
* @throws MalformedURLException 
*/
public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub

Model instances = ModelFactory.createDefaultModel();
instances.read ("file:dataset.txt","N3");
Reasoner reasoner = new  
                    GenericRuleReasoner(Rule.rulesFromURL("file:rule.txt"));
reasoner.setDerivationLogging(true);
InfModel inf = ModelFactory.createInfModel(reasoner, instances); 

        //print out the statements in the model
StmtIterator iter = inf.listStatements();
while (iter.hasNext()) {
   Statement stmt      = iter.nextStatement();  
   Resource  subject   = stmt.getSubject();     
   Property  predicate = stmt.getPredicate();   
   RDFNode   object    = stmt.getObject();      

   System.out.print(subject.toString());
   System.out.print(" " + predicate.toString() + " ");
   if (object instanceof Resource) {
      System.out.print(object.toString());
   } else {
       // object is a literal
       System.out.print(" \"" + object.toString() + "\"");
   }
   System.out.println(" .");

}
}

7) Run this Java application and you should see the following in the console:


http://oanaureche.com/prefix#John http://jena.hpl.hp.com/prefix#uncle http://oanaureche.com/prefix#Mary .

http://oanaureche.com/prefix#John http://jena.hpl.hp.com/prefix#brother http://oanaureche.com/prefix#Joseph .

http://oanaureche.com/prefix#Joseph http://jena.hpl.hp.com/prefix#father http://oanaureche.com/prefix#Mary .


The reasoner inferred a third statement: that John is the uncle of Mary. Pretty cool!


Sunday 21 October 2012

Source code to XML and RDF converters

I moved all the converters to one place:

http://swifc-converters.appspot.com/

I have developed two prototypes for converting PHP or Java code to XML and RDF. You can find them at the following addresses:

http://xmltranslator.appspot.com/sourcecodetoxml.html

and

http://rdfconverter.appspot.com/sourcecodetordf.html

As an extra tool, I also have running a general XML to RDF converter:

http://xmltordf.appspot.com/xmltordf.html

If you encounter any issues, please leave a comment. I would be happy to fix whatever issues..



Wednesday 17 October 2012

Apache Tomcat HTTP Status 500 - javax.servlet.ServletException: java.lang.UnsupportedClassVersionError


HTTP Status 500 - javax.servlet.ServletException: java.lang.UnsupportedClassVersionError: com/namespace/project/class : Unsupported major.minor version 51.0 (unable to load class com.namespace.project.class)


If you've seen an error like this when trying to run a Tomcat project, the problem is that the JAVA version used to compile the class mentioned in the error is different than the JAVA version Tomcat uses. You can either recompile the class or change the JAVA version Tomcat uses.

To change the settings for Tomcat, in Windows, modify the catalina.bat file by adding the following line in red. You most probably have a different location for your JDK. This version is the version used for compiling the class that gives the error. After adding the line remember to restart Tomcat (shutdown.bat and startup.bat) if it is already running.

rem set TITLE=Tomcat.Cluster#1.Server#1 [%DATE% %TIME%]
rem
rem $Id: catalina.bat 1344732 2012-05-31 14:08:02Z kkolinko $
rem -----------------------------------------------------------

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_33

rem Suppress Terminate batch job on CTRL+C
if not ""%1"" == ""run"" goto mainEntry
if "%TEMP%" == "" goto mainEntry
if exist "%TEMP%\%~nx0.run" goto mainEntry

Wednesday 10 October 2012

Merge a branch into the trunk using Tortoise SVN

We'll assume you have done some changes in the branch that you are working on and you want to merge those changes into the trunk. Here I will outline some steps using the svn command line tool and the TortoiseSVN tool using Windows 7.

1) Checkout the branches and trunk from SVN (if you do not have a local copy) using command line for example:

    svn checkout link_to_svn_repository WRK --username your_username

2) Browse to the folder where your working copy is located (e.g, where you previously checked out) and using TortoiseSVN tool, right click on trunk and choose Merge...


After choosing Merge, next choose reintegrate a branch:




click Next and choose which one of the existing branches to reintegrate:

4) Click Next -> Merge and wait for completion

5) The trunk has now new changes, so commit the changes back into the SVN:


    svn commit -m "Reintegrate branch 1.2"







Tuesday 9 October 2012

How to run multiple python test cases

If you have the following situation: multiple python test cases in a directory and you want to automatically run them with only one command, first you need to install the discover python module, which is actually called python nose module. In Ubuntu you would typically run the following from command line:


$ sudo apt-get install python-nose

After successfully installing the discovery module, navigate to the folder where your test cases are located and just run:

$ nosetests

This will automatically find the tests and run them for you. 

Note: I believe that the test file names need to follow a convention; please consult the documentation of the module. I tried with "name_test.py" and it worked.

Monday 8 October 2012

How to run an XQuery script


First, for the XQuery processor (the one that I use in the following steps) to work you need to have Java installed.

1) Download an XQuery processor for Java. I used Saxon. If you don't have material resources (like myself) download the home edition. You'll need to pay for the commercial ones if you choose to use one. When I wrote this article I downloaded SaxonHE9-4-0-6J.zip from the following link:

http://sourceforge.net/projects/saxon/files/Saxon-HE/9.4/

2) Extract the zip file to a path you can remember. It will result in 2 jar files:
3) Run your XQuery script by adding the extracted saxon9he.jar file to your java classpath:

java -classpath C:\.....\saxon9he.jar net.sf.saxon.Query my.xquery

where my.xquery is your xquery script, e.g.


<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:bibterms="http://www.book-stuff.com/terms/">

    <rdf:Description rdf:about="http://www.book-stuff.com/bib">
    {
        for $book in doc( "bib.xml" )//book
        return 
            <bibterms:book rdf:parseType="Resource">
            </bibterms:book>
    }
    </rdf:Description>

</rdf:RDF>

This command will output the resulting RDF file on the console. If you prefer having the result in a file, just add > filename.ext to the command, e.g:


java -classpath C:\.....\saxon9he.jar net.sf.saxon.Query my.xquery > result.rdf


Sunday 13 May 2012

Install a network printer in Windows 7

Go to Start -> Control Panel

In the Category under Hardware and Sound select View devices and printers:


and in the next window click on Add a printer and Add a network, wireless or Bluetooth printer. Windows will start searching for available printer. When you'll see the name of the printer you want to connect to select it. Windows should automatically look for drivers for that printer.

Thursday 10 May 2012

Erratic movements of mouse cursor?

It so happens that when typing fast the palm of your hand touches the touch pad of your laptop and the cursor moves, this causing you to type in an undesired location. There is a tool for Windows that can temporarily freeze the touch pad while you write text. It's called touchfreeze and you can download it from here:

http://code.google.com/p/touchfreeze/

Wednesday 9 May 2012

ERROR 2003 (HY000): Can't connect to MySQL server on 'ip_address' (110)

If you came across this error, because it is in the 2000's error codes then it is a MySQL client error, this means that the connection that you are trying to establish doesn't reach the server, it stops somewhere before that.

If you are trying to connect to a remote MySQL server one common cause it's the firewall on the MySQL server host machine.

You'll have to set some exceptions for your firewall. So if you have Windows 7 do the following:

Control Panel -> Windows Firewall -> Allow a program of Feature through Windows Firewall



Once in the "Allow programs to communicate through Windows Firewall" click the button "Allow another program.."


and if it's not in the list that appears after clicking the button browse to the location where the executable is placed. In my case is:

"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe"

After you find the executable select it, click Open and in the next window click Add.

This will take you back to the  "Allow programs to communicate through Windows Firewall" window. Click OK.


XAMPP new security concept

"access to the requested directory is only available from the local network"
To fix this issue quick and dirty:
Comment the last LocationMatch node in  C:\XAMPP\apache\conf\extra\httpd-xampp.conf


Example:


#Close XAMPP sites here
#<LocationMatch "^/(?i:(?:xampp|license|phpmyadmin))">
#        Order deny,allow
#        Deny from all
#        Allow from ::1 127.0.0.0/8
#        ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
#</LocationMatch>


or set your own restrictions.

Sunday 6 May 2012

Yahoo messenger not working on Windows 7?

Yahoo messenger throws Library exceptions?

Make sure you get the right version for your system.. You can download one from here:

http://www.windows7download.com/win7-yahoo-messenger/oycgtfpl.html


Apache restrict access to selected directories based on IP address

Apache let's you restrict access to selected directories using the mod_authz_host module.
To restrict access one option is to modify the httpd.conf file (in your Apache root folder). By default, your Apache configuration allows access to anyone. My original httpd.conf file has a section like the following:


<Directory "C:/xampp/htdocs">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks Includes ExecCGI


    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride All


    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all


</Directory>


Note that an .htaccess file placed in a selected directory will override the access set in the httpd.conf file.


C:/xampp/htdocs is my Apache root folder so if I want to restrict access to only localhost, the restriction would be:


<Directory "C:/xampp/htdocs">
    
    Order deny,allow
    Allow from 127.0.0.1


</Directory>


after making changes, restart Apache. You first deny access to all (which is the default behaviour) and then allow access to localhost.



Can't restart Apache from XAMPP?

Use the command line and run cmd as Administrator:




C:\>net stop Apache2.2

respectively,

C:\>net start Apache2.2

Apache not starting on Windows 7

If you have installed XAMPP on Windows 7 and Apache won't start although no application is using port 80 then uninstall XAMPP and install it again by right-clicking on the XAMPP executable and selecting Run as adimistrator. You'll have to unblock Apache, but Windows should give you that option in the process of installing XAMPP.

To check if any application is using port 80, run from the command line


C:\>netstat -o -a -n

-o   Displays the process id of active connections
-a   Displays all active connections and the TCP and UDP ports on which the computer is listening
-n   Displays active TCP connections, however, addresses and port numbers are expressed numerically and no attempt is made to determine names

and look for 0.0.0.0:80. You'll have something similar to:

Active Connections

  Proto     Local Address          Foreign Address           State                PID
  TCP         0.0.0.0:80                 0.0.0.0:0              LISTENING         2584
  TCP         0.0.0.0:135               0.0.0.0:0              LISTENING         804
  TCP         0.0.0.0:443               0.0.0.0:0              LISTENING         408
  TCP         0.0.0.0:445               0.0.0.0:0              LISTENING           4

For me, the application that is using port 80 has PID 408. You can use PID to track down which application is it. To find out which application has a specific process id, open the Task Manager by using the CTRL+ALT+DEL keyboard combination and click on the Processes tab. In my case is the Apache HTTP server that has the 2584 process ID:



If the PID column does not show up, you can view it by going to View-> Select Columns in the window menu. Clicking on the PID tab will sort the PID entries.

Also as a quick note, Skype might use port 80 and 443 (SSL). In order to make Skype use other ports, open Skype and go to Tools -> Options.. -> Advanced -> Connection and deselect "Use port 80 and 443 as alternatives for incoming connections"

Where to download a free trial of Microsoft Office

Go to:

http://office.microsoft.com/en-us/home-and-student

and click the Download a free trial link under the payment selection box.

You'll have to register with them if you don't have an account already. Presumably the free trial is for 60 days. Along the process you'll get a serial key to activate your free copy.

Make a website publicly accessible with port forwarding linksys router

As the title says... here is a link I have found on Youtube

http://www.youtube.com/watch?v=pIK-RpVNAM8