|
From: <cw...@us...> - 2007-06-19 15:48:57
|
Revision: 448
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=448&view=rev
Author: cweiske
Date: 2007-06-19 08:48:52 -0700 (Tue, 19 Jun 2007)
Log Message:
-----------
Add ORDER BY dateTime support
Modified Paths:
--------------
trunk/rdfapi-php/api/sparql/SparqlEngineDb/TypeSorter.php
trunk/rdfapi-php/test/unit/Sparql/SparqlDbTests_test.php
trunk/rdfapi-php/test/unit/Sparql/cases.php
Added Paths:
-----------
trunk/rdfapi-php/test/unit/Sparql/data/data-sort-datetime.n3
trunk/rdfapi-php/test/unit/Sparql/query/query-sort-datetime.rq
trunk/rdfapi-php/test/unit/Sparql/result/sort-datetime.res
Modified: trunk/rdfapi-php/api/sparql/SparqlEngineDb/TypeSorter.php
===================================================================
--- trunk/rdfapi-php/api/sparql/SparqlEngineDb/TypeSorter.php 2007-06-13 16:26:58 UTC (rev 447)
+++ trunk/rdfapi-php/api/sparql/SparqlEngineDb/TypeSorter.php 2007-06-19 15:48:52 UTC (rev 448)
@@ -26,7 +26,10 @@
* @var array
*/
public static $arCastTypes = array(
- 'http://www.w3.org/2001/XMLSchema#integer' => 'SIGNED INTEGER'
+ 'http://www.w3.org/2001/XMLSchema#integer' => 'SIGNED INTEGER',
+ //yes, this does not work with multiple time zones.
+ 'http://www.w3.org/2001/XMLSchema#dateTime' => 'CHAR',
+ 'http://www.w3.org/2001/XMLSchema#date' => 'CHAR',
);
Modified: trunk/rdfapi-php/test/unit/Sparql/SparqlDbTests_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/SparqlDbTests_test.php 2007-06-13 16:26:58 UTC (rev 447)
+++ trunk/rdfapi-php/test/unit/Sparql/SparqlDbTests_test.php 2007-06-19 15:48:52 UTC (rev 448)
@@ -9,7 +9,7 @@
require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php';
require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine.php';
require_once RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphMem.php';
-//require_once 'Console/Color.php';
+require_once 'Console/Color.php';
class testSparqlDbTests extends UnitTestCase
{
@@ -76,6 +76,9 @@
} catch (Exception $e) {
$bOk = false;
$t = null;
+ //an exception is an error
+ var_dump($e->getMessage());
+ $this->assertTrue(false);
}
/*
if (!$bOk) {
Modified: trunk/rdfapi-php/test/unit/Sparql/cases.php
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/cases.php 2007-06-13 16:26:58 UTC (rev 447)
+++ trunk/rdfapi-php/test/unit/Sparql/cases.php 2007-06-19 15:48:52 UTC (rev 448)
@@ -22,7 +22,7 @@
'tests' => 'sparql_limitOffset_tests',
'checkfunc' => 'resultCheckSort'
),
- 'filter' => array(
+ 'filter' => array(//'deact'=>1,
'title' => 'filter tests',
'tests' => 'sparql_filter_tests',
'checkfunc' => 'resultCheck'
@@ -86,6 +86,7 @@
$_SESSION['sparql_sort_tests'] = array(
+
1 => array('data' => 'data-sort-4.n3',
'query' => "query-sort-5",
'result' => "sort5") ,
@@ -118,6 +119,9 @@
'query' => "query-sort-4",
'result' => "sort8") ,
+ 9 => array('data' => "data-sort-datetime.n3",
+ 'query' => "query-sort-datetime",
+ 'result' => "sort-datetime") ,
);
Added: trunk/rdfapi-php/test/unit/Sparql/data/data-sort-datetime.n3
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/data/data-sort-datetime.n3 (rev 0)
+++ trunk/rdfapi-php/test/unit/Sparql/data/data-sort-datetime.n3 2007-06-19 15:48:52 UTC (rev 448)
@@ -0,0 +1,6 @@
+@prefix dc: <http://purl.org/dc/elements/1.1/> .
+
+_:a dc:created "2004-12-31T18:01:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
+_:b dc:created "2004-01-31T18:01:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
+_:c dc:created "2007-03-12T17:02:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
+_:d dc:created "2007-03-12T17:01:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
Added: trunk/rdfapi-php/test/unit/Sparql/query/query-sort-datetime.rq
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/query/query-sort-datetime.rq (rev 0)
+++ trunk/rdfapi-php/test/unit/Sparql/query/query-sort-datetime.rq 2007-06-19 15:48:52 UTC (rev 448)
@@ -0,0 +1,5 @@
+PREFIX dc: <http://purl.org/dc/elements/1.1/>
+
+SELECT ?created
+WHERE { ?x dc:created ?created }
+ORDER BY ASC(?created)
Added: trunk/rdfapi-php/test/unit/Sparql/result/sort-datetime.res
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/result/sort-datetime.res (rev 0)
+++ trunk/rdfapi-php/test/unit/Sparql/result/sort-datetime.res 2007-06-19 15:48:52 UTC (rev 448)
@@ -0,0 +1,19 @@
+$result = array();
+$res1 = new Literal("2004-12-31T18:01:00-05:00");
+$res2 = new Literal("2004-01-31T18:01:00-05:00");
+$res3 = new Literal("2007-03-12T17:02:00-05:00");
+$res4 = new Literal("2007-03-12T17:01:00-05:00");
+
+$res1->setDatatype("http://www.w3.org/2001/XMLSchema#dateTime");
+$res2->setDatatype("http://www.w3.org/2001/XMLSchema#dateTime");
+$res3->setDatatype("http://www.w3.org/2001/XMLSchema#dateTime");
+$res4->setDatatype("http://www.w3.org/2001/XMLSchema#dateTime");
+
+
+
+$result = array(
+ array('?created' => $res2),
+ array('?created' => $res1),
+ array('?created' => $res4),
+ array('?created' => $res3),
+);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-06-19 17:04:47
|
Revision: 450
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=450&view=rev
Author: cweiske
Date: 2007-06-19 10:04:46 -0700 (Tue, 19 Jun 2007)
Log Message:
-----------
Fix exception when no variables can be returned -> return empty array
Modified Paths:
--------------
trunk/rdfapi-php/api/sparql/SparqlEngineDb/SqlGenerator.php
trunk/rdfapi-php/test/config.php.dist
Modified: trunk/rdfapi-php/api/sparql/SparqlEngineDb/SqlGenerator.php
===================================================================
--- trunk/rdfapi-php/api/sparql/SparqlEngineDb/SqlGenerator.php 2007-06-19 16:13:07 UTC (rev 449)
+++ trunk/rdfapi-php/api/sparql/SparqlEngineDb/SqlGenerator.php 2007-06-19 17:04:46 UTC (rev 450)
@@ -241,10 +241,13 @@
}
foreach ($arSelect as $nUnionCount => $arSelectPart) {
$arSelectPart = self::removeNull($arSelectPart);
- if (count($arSelectPart) == 0) {
- throw new SparqlEngineDb_SqlGeneratorException('No variable that could be returned.');
+ if (count($arSelectPart) == 0
+ || (count($arSelectPart) == 1 && $arSelectPart[0] == '')) {
+ //test "test-1-07" suggests we return no rows in this case
+ //throw new SparqlEngineDb_SqlGeneratorException('No variable that could be returned.');
+ } else {
+ $arStrSelect[$nUnionCount] = strtoupper($strSelectType) . ' ' . implode(', ' , $arSelectPart);
}
- $arStrSelect[$nUnionCount] = strtoupper($strSelectType) . ' ' . implode(', ' , $arSelectPart);
}
break;
@@ -259,7 +262,7 @@
}
$arSqls = array();
- foreach ($arSelect as $nUnionCount => $arSelectPart) {
+ foreach ($arStrSelect as $nUnionCount => $arSelectPart) {
$arSqls[] = array(
'select' => $arStrSelect[$nUnionCount],
'from' => ' FROM ' . implode(' ' , self::removeNull($arFrom[$nUnionCount])),
Modified: trunk/rdfapi-php/test/config.php.dist
===================================================================
--- trunk/rdfapi-php/test/config.php.dist 2007-06-19 16:13:07 UTC (rev 449)
+++ trunk/rdfapi-php/test/config.php.dist 2007-06-19 17:04:46 UTC (rev 450)
@@ -18,5 +18,8 @@
'password' => ''
);
+//enable this to get more informatin about failing unit tests
+//$GLOBALS['debugTests'] = true;
+
define('LOG', false);
?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-12 11:24:19
|
Revision: 483
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=483&view=rev
Author: cweiske
Date: 2007-08-12 04:24:06 -0700 (Sun, 12 Aug 2007)
Log Message:
-----------
Fix bug #1772578: N3Parser infinite loop
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Parser.php
trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Parser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-12 11:03:13 UTC (rev 482)
+++ trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-12 11:24:06 UTC (rev 483)
@@ -68,7 +68,7 @@
**/
function N3Parser() {
//Regular expressions:
- $Name = '[A-Za-z0-9_@\.]+[^\.,;\[\]\s ]*';
+ $Name = '[A-Za-z0-9_@\.]+[^\.,;\[\]\s\) ]*';
$URI = '<[^> ]*>';
$bNode = '_:'.$Name;
$Univar = '\?'.$Name;
@@ -439,7 +439,6 @@
$res=array();
preg_match_all($this->Tokens, $s, $newres);
-
$res=$this->array_concat($res, array_map('trim', $newres[0]));
return $res;
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-12 11:03:13 UTC (rev 482)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-12 11:24:06 UTC (rev 483)
@@ -8,7 +8,7 @@
* Tests the N3Parser
*
* @version $Id$
- * @author Tobias Gau\xDF <tob...@we...>
+ * @author Tobias Gau� <tob...@we...>
*
* @package unittests
* @access public
@@ -17,7 +17,7 @@
class testN3Parser extends UnitTestCase {
function testN3Parser() {
$this->UnitTestCase();
-
+
$_SESSION['n3TestInput']='
@prefix p: <http://www.example.org/personal_details#> .
@prefix m: <http://www.example.org/meeting_organization#> .
@@ -26,7 +26,7 @@
p:GivenName "Fred";
p:hasEmail <mailto:fr...@ex...>;
m:attending <http://meetings.example.com/cal#m1> .
-
+
<http://meetings.example.com/cal#m1>
m:homePage <http://meetings.example.com/m1/hp> .
';
@@ -34,20 +34,20 @@
}
function testIsMemmodel() {
-
+
// Import Package
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
$n3pars= new N3Parser();
- $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
+ $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
$this->assertIsA($model, 'memmodel');
}
-
+
function testParsing() {
-
+
$n3pars= new N3Parser();
- $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
-
-
+ $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
+
+
$model2 = new MemModel();
// Ceate new statements and add them to the model
@@ -63,17 +63,17 @@
$statement4 = new Statement(new Resource("http://meetings.example.com/cal#m1"),
new Resource("http://www.example.org/meeting_organization#homePage"),
new Resource("http://meetings.example.com/m1/hp"));
-
-
+
+
$model2->add($statement1);
$model2->add($statement2);
$model2->add($statement3);
$model2->add($statement4);
-
+
$this->assertTrue($model->containsAll($model2));
}
-
+
function testPrefixNotDeclared() {
$rdfInput='
@prefix m: <http://www.example.org/meeting_organization#>.
@@ -85,11 +85,11 @@
';
$n3pars= new N3Parser();
- $model=$n3pars->parse2model($rdfInput,false);
- //var_dump($model);
+ $model=$n3pars->parse2model($rdfInput,false);
+ //var_dump($model);
$this->assertErrorPattern('[Prefix not declared: p:]');
}
-
+
function testLoneSemicolon() {
$n3 = '<a> <b> <c> ; .';
$parser = &new N3Parser();
@@ -97,5 +97,14 @@
$this->assertEqual(1, $model->size());
$this->assertNoErrors();
}
+
+ function testTightClosingList() {
+ $n3 = '@prefix : <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql4/manifest#> .
+ @prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
+ <> mf:entries ( mf:syn-09) .';
+ $parser = &new N3Parser();
+ $model = &$parser->parse2model($n3, false);
+ //if bug occured, the parser would be in an endless loop
+ }
}
?>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 04:59:47
|
Revision: 495
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=495&view=rev
Author: cweiske
Date: 2007-08-12 21:59:45 -0700 (Sun, 12 Aug 2007)
Log Message:
-----------
Add support for plain numbers and booleans in N3 files.
This fixes bug #1545380: N3 parser doesn't understand numeric literals
and allows me to go on integrating the new DAWG tests
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Parser.php
trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Parser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-12 18:10:08 UTC (rev 494)
+++ trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-13 04:59:45 UTC (rev 495)
@@ -77,7 +77,8 @@
$Univar = '\?'.$Name;
$QName = '(?:[A-Za-z][A-Za-z0-9_@\.]*)?:'.$Name;
$Literal = '"(\\\"|[^"])*"'; # '"(?:\\"|[^"])*"'
- $Number = '[0-9]+(:?[\\.e][0-9]+)?';
+ $Number = '[-+]?[0-9]+(\\.[0-9]+)?([eE][-+]?[0-9]+)?';
+ $Boolean = '@(?:true|false)';
// $Literal = '"[^"\\\\]*(?:\\.\\[^"\\]*)*"'; # '"(?:\\"|[^"])*"'
$LangTag = '@[A-Za-z\-]*[^ \^\.\;\,]';
$Datatype = '(\^\^)[^ ,\.;)]+';
@@ -85,17 +86,23 @@
// $LLiteral = '"""[^"\\\\]*(?:(?:.|"(?!""))[^"\\\\]*)*"""';
$LLiteral = '"""[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""';
// '"""[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
- $Comment = '#.*$';
- $Prefix = '(?:[A-Za-z][A-Za-z0-9_]*)?:';
+ $Comment = '#.*$';
+ $Prefix = '(?:[A-Za-z][A-Za-z0-9_]*)?:';
$PrefixDecl = '@prefix';
- $WS = '[ \t]';
+ $WS = '[ \t]';
$this->RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; # for 'a' keyword
$this->DAML_NS = 'http://www.daml.org/2001/03/daml+oil#'; # for '=' keyword
$this->OWL_NS = 'http://www.w3.org/2002/07/owl#';
// $t = array( $LLiteral, $URI); //, $Literal, $PrefixDecl, $QName, $bNode, $Prefix,
// $Univar, 'a', '{', '}', '\(', '\)', '\[', '\]', ',', ';', '\.', $WS, $Comment);
- $t = array( $Datatype_URI,$Datatype,$LLiteral, $URI, $Literal, $PrefixDecl, $QName, $Number, $bNode, $Prefix, $Univar, 'a','=', '{', '}', '\(', '\)', '\[', '\]', ',', ';', '\.', $WS, $Comment,$LangTag);
+ $t = array(
+ $Datatype_URI, $Datatype, $LLiteral, $URI, $Literal,
+ $PrefixDecl, $QName, $Number, $Boolean, $bNode,
+ $Prefix, $Univar, 'a','=',
+ '{', '}', '\(', '\)', '\[', '\]', ',', ';', '\.',
+ $WS, $Comment,$LangTag
+ );
$this->Tokens = "/(".join($t,"|").")/m";
$this->bNode = 0;
@@ -545,7 +552,8 @@
array_walk($list, array($this, 'replace_equal'));
array_walk($list, array($this, 'replace_this'));
- for ($i=0; $i<count($list); $i++) {
+ for ($i = 0; $i < count($list); $i++) {
+
if ($list[$i]=='<>') {
if (!isset($path)) {
if (!isset($_SERVER['SERVER_ADDR'])) {
@@ -561,20 +569,28 @@
};
- if ((!strstr('<_"?.;,{}[]()@',$list[$i]{0}))
- && (substr($list[$i],0,3)!='^^<')
+ if (preg_match('/^[-+]?[0-9]+$/', $list[$i])) {
+ //integer
+ $list[$i] = intval($list[$i]);
+ } else if (is_numeric($list[$i])) {
+ //float or decimal
+ // After conversion we cannot distinguish between both
+ $list[$i] = floatval($list[$i]);
+ } else if ((!strstr('<_"?.;,{}[]()@', $list[$i]{0}))
+ && (substr($list[$i],0,3) != '^^<')
) {
- $_r = explode(":",$list[$i]);
- $ns = $_r[0].':';
+ //prefix or unknown
+ $_r = explode(':', $list[$i]);
+ $ns = $_r[0] . ':';
$name = $_r[1];
if (isset($prefixes[$ns])) {
$list[$i] = '<'.$prefixes[$ns].$name.'>';
- } else if (isset($prefixes[substr($ns,2)])) {
- $list[$i] = '^^'.$prefixes[substr($ns,2)].$name.'';
+ } else if (isset($prefixes[substr($ns, 2)])) {
+ $list[$i] = '^^' . $prefixes[substr($ns, 2)] . $name . '';
} else {
- #die('Prefix not declared:'.$ns);
- $this->parseError=true;
+ //die('Prefix not declared:'.$ns);
+ $this->parseError = true;
trigger_error('Prefix not declared: '.$ns, E_USER_ERROR);
break;
}
@@ -602,7 +618,9 @@
}
if (substr($list[$i],0,2)=='^^') {
- if ($list[$i][2]!='<'){$list[$i]='^^<'.substr($list[$i],2).'>';};
+ if ($list[$i][2]!='<') {
+ $list[$i] = '^^<' . substr($list[$i], 2) . '>';
+ }
};
}//foreach list item
@@ -999,67 +1017,94 @@
$t = $this->getStatements($t); # get all of the "statements" from the stream
foreach ($t as $stat) {
- $stats=$this->statementize($stat);
+ $stats = $this->statementize($stat);
foreach ($stats as $y) {
- $result[]=$y;
+ $result[]=$y;
}
}
+
// for x in [statementize(stat) for stat in t] {
// for y in x: result.append(y)
return $result;
}
- /**
- * Constructs a RAP RDFNode from URI/Literal/Bnode
- * @access private
- * @param string $s
- * @returns object RDFNode
- **/
- function toRDFNode($s,$state) {
- $ins=substr($s,1,-1);
- if ($s{0}=="\"") {
- $lang=NULL;
+ /**
+ * Constructs a RAP RDFNode from URI/Literal/Bnode
+ * @access private
+ * @param string $s
+ * @returns object RDFNode
+ **/
+ function toRDFNode($s, $state)
+ {
+ $ins = substr($s, 1, -1);
+ if ($s{0} == '"') {
+ $lang = NULL;
- if (count($state)>3) {
+ if (count($state)>3) {
+ for ($i = 3; $i < count($state); $i++) {
+ if ($state[$i][0]=='@') {
+ $lang = substr($state[3], 1);
+ }
+ if (substr($state[$i],0,2) == '^^') {
+ $dtype = substr($state[$i],2);
+ if ($dtype[0]=='<') {
+ $dtype = substr($dtype,1,-1);
+ }
+ }
+ }
+ }
- for ($i = 3; $i < count($state); $i++){
- if ($state[$i][0]=='@')$lang=substr($state[3],1);
- if (substr($state[$i],0,2)=='^^'){
+ if (UNIC_RDF) {
+ $ins = $this->str2unicode_nfc($ins);
+ }
+ $new_Literal = new Literal($ins, $lang);
+ if (isset($dtype)) {
+ $new_Literal->setDatatype($dtype);
+ }
+ return $new_Literal;
+ } else if (is_int($s)) {
+ $value = new Literal($s);
+ $value->setDatatype(XML_SCHEMA . 'integer');
+ return $value;
+ } else if (is_float($s)) {
+ $value = new Literal($s);
+ $value->setDatatype(XML_SCHEMA . 'double');
+ return $value;
+ } else if ($s == '@true') {
+ $value = new Literal(true);
+ $value->setDatatype(XML_SCHEMA . 'boolean');
+ return $value;
+ } else if ($s == '@false') {
+ $value = new Literal(false);
+ $value->setDatatype(XML_SCHEMA . 'boolean');
+ return $value;
+ }
- $dtype=substr($state[$i],2);
- if ($dtype[0]=='<') $dtype= substr($dtype,1,-1);
+ if (strstr($s, '_' . BNODE_PREFIX)) {
+ if (($this->FixBnodes) || (!array_search($s,$this->bNodeMap))) {
+ return new BlankNode($ins);
+ } else {
+ return new BlankNode(
+ trim(
+ substr(
+ array_search($s, $this->bNodeMap),
+ 2
+ )
+ )
+ );
+ };
+ }
- };
+ return new Resource($ins);
+ }//function toRDFNode($s, $state)
- };
- };
- if(UNIC_RDF){
- $ins=$this->str2unicode_nfc($ins);
- }
- $new_Literal=new Literal($ins,$lang);
- if (isset($dtype)) $new_Literal->setDatatype($dtype);
- return $new_Literal;
- };
- if (strstr($s,'_'.BNODE_PREFIX)) {
- if (($this->FixBnodes) OR (!array_search($s,$this->bNodeMap))) {
- return new BlankNode($ins);
- } else {return new BlankNode(trim(substr(array_search($s,$this->bNodeMap),2)));
- };
- }
-
- return new Resource($ins);
- }
-
-
-
-
} //end: N3Parser
?>
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-12 18:10:08 UTC (rev 494)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-13 04:59:45 UTC (rev 495)
@@ -1,4 +1,5 @@
<?php
+require_once RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3;
// ----------------------------------------------------------------------------------
// Class: testN3Parser
@@ -8,103 +9,207 @@
* Tests the N3Parser
*
* @version $Id$
- * @author Tobias Gau� <tob...@we...>
+ * @author Tobias Gauss <tob...@we...>
+ * @author Christian Weiske <cw...@cw...?
*
* @package unittests
* @access public
*/
- class testN3Parser extends UnitTestCase {
- function testN3Parser() {
- $this->UnitTestCase();
+class testN3Parser extends UnitTestCase
+{
- $_SESSION['n3TestInput']='
- @prefix p: <http://www.example.org/personal_details#> .
- @prefix m: <http://www.example.org/meeting_organization#> .
+ function testN3Parser() {
+ $this->UnitTestCase();
- <http://www.example.org/people#fred>
- p:GivenName "Fred";
- p:hasEmail <mailto:fr...@ex...>;
- m:attending <http://meetings.example.com/cal#m1> .
+ $_SESSION['n3TestInput']='
+ @prefix p: <http://www.example.org/personal_details#> .
+ @prefix m: <http://www.example.org/meeting_organization#> .
- <http://meetings.example.com/cal#m1>
- m:homePage <http://meetings.example.com/m1/hp> .
- ';
+ <http://www.example.org/people#fred>
+ p:GivenName "Fred";
+ p:hasEmail <mailto:fr...@ex...>;
+ m:attending <http://meetings.example.com/cal#m1> .
+ <http://meetings.example.com/cal#m1>
+ m:homePage <http://meetings.example.com/m1/hp> .
+ ';
- }
- function testIsMemmodel() {
- // Import Package
- include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
- $n3pars= new N3Parser();
- $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
- $this->assertIsA($model, 'memmodel');
- }
+ }
+ function testIsMemmodel() {
- function testParsing() {
+ // Import Package
+ $n3pars= new N3Parser();
+ $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
+ $this->assertIsA($model, 'memmodel');
+ }
- $n3pars= new N3Parser();
- $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
+ function testParsing() {
+ $n3pars= new N3Parser();
+ $model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
- $model2 = new MemModel();
- // Ceate new statements and add them to the model
- $statement1 = new Statement(new Resource("http://www.example.org/people#fred"),
- new Resource("http://www.example.org/personal_details#hasEmail"),
- new Resource("mailto:fr...@ex..."));
- $statement2 = new Statement(new Resource("http://www.example.org/people#fred"),
- new Resource("http://www.example.org/meeting_organization#attending"),
- new Resource("http://meetings.example.com/cal#m1"));
- $statement3 = new Statement(new Resource("http://www.example.org/people#fred"),
- new Resource("http://www.example.org/personal_details#GivenName"),
- new Literal("Fred"));
- $statement4 = new Statement(new Resource("http://meetings.example.com/cal#m1"),
- new Resource("http://www.example.org/meeting_organization#homePage"),
- new Resource("http://meetings.example.com/m1/hp"));
+ $model2 = new MemModel();
+ // Ceate new statements and add them to the model
+ $statement1 = new Statement(new Resource("http://www.example.org/people#fred"),
+ new Resource("http://www.example.org/personal_details#hasEmail"),
+ new Resource("mailto:fr...@ex..."));
+ $statement2 = new Statement(new Resource("http://www.example.org/people#fred"),
+ new Resource("http://www.example.org/meeting_organization#attending"),
+ new Resource("http://meetings.example.com/cal#m1"));
+ $statement3 = new Statement(new Resource("http://www.example.org/people#fred"),
+ new Resource("http://www.example.org/personal_details#GivenName"),
+ new Literal("Fred"));
+ $statement4 = new Statement(new Resource("http://meetings.example.com/cal#m1"),
+ new Resource("http://www.example.org/meeting_organization#homePage"),
+ new Resource("http://meetings.example.com/m1/hp"));
- $model2->add($statement1);
- $model2->add($statement2);
- $model2->add($statement3);
- $model2->add($statement4);
+ $model2->add($statement1);
+ $model2->add($statement2);
+ $model2->add($statement3);
+ $model2->add($statement4);
- $this->assertTrue($model->containsAll($model2));
- }
- function testPrefixNotDeclared() {
- $rdfInput='
- @prefix m: <http://www.example.org/meeting_organization#>.
+ $this->assertTrue($model->containsAll($model2));
+ }
- <http://www.example.org/people#fred>
- p:GivenName "Fred";
- p:hasEmail <mailto:fr...@ex...>;
- m:attending <http://meetings.example.com/cal#m1> .
- ';
+ function testPrefixNotDeclared() {
+ $rdfInput='
+ @prefix m: <http://www.example.org/meeting_organization#>.
- $n3pars= new N3Parser();
- $model=$n3pars->parse2model($rdfInput,false);
- //var_dump($model);
- $this->assertErrorPattern('[Prefix not declared: p:]');
- }
+ <http://www.example.org/people#fred>
+ p:GivenName "Fred";
+ p:hasEmail <mailto:fr...@ex...>;
+ m:attending <http://meetings.example.com/cal#m1> .
+ ';
- function testLoneSemicolon() {
- $n3 = '<a> <b> <c> ; .';
- $parser = &new N3Parser();
- $model = &$parser->parse2model($n3, false);
- $this->assertEqual(1, $model->size());
- $this->assertNoErrors();
- }
+ $n3pars= new N3Parser();
+ $model=$n3pars->parse2model($rdfInput,false);
+ //var_dump($model);
+ $this->assertErrorPattern('[Prefix not declared: p:]');
+ }
- function testTightClosingList() {
- $n3 = '@prefix : <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql4/manifest#> .
- @prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
- <> mf:entries ( mf:syn-09) .';
- $parser = &new N3Parser();
- $model = &$parser->parse2model($n3, false);
- //if bug occured, the parser would be in an endless loop
- }
+ function testLoneSemicolon() {
+ $n3 = '<a> <b> <c> ; .';
+ $parser = &new N3Parser();
+ $model = &$parser->parse2model($n3, false);
+ $this->assertEqual(1, $model->size());
+ $this->assertNoErrors();
}
+
+ function testTightClosingList() {
+ $n3 = '@prefix : <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql4/manifest#> .
+ @prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
+ <> mf:entries ( mf:syn-09) .';
+ $parser = &new N3Parser();
+ $model = &$parser->parse2model($n3, false);
+ //if bug occured, the parser would be in an endless loop
+ }
+
+
+
+ /**
+ * Check number parsing
+ * @see http://www.w3.org/2000/10/swap/grammar/n3-report.html#node
+ */
+ function testNumbers()
+ {
+ $n3 = '@prefix : <http://example.org/#> .
+ :foo :bar 0.7 .
+ :foo :bar 42 .
+ :foo :bar 10e6 .
+
+ :foo :bar -0.7 .
+ :foo :bar -42 .
+ :foo :bar -12E-6 .
+ ';
+ $parser = &new N3Parser();
+
+ $model = &$parser->parse2model($n3, false);
+
+ $model2 = new MemModel();
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(0.7, null, XML_SCHEMA . 'double')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(42, null, XML_SCHEMA . 'integer')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(10e6, null, XML_SCHEMA . 'double')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(-0.7, null, XML_SCHEMA . 'double')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(-42, null, XML_SCHEMA . 'integer')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(-12E-6, null, XML_SCHEMA . 'double')
+ )
+ );
+
+ $this->assertEqual(6, $model->size());
+ $this->assertTrue($model->containsAll($model2));
+ }//function testNumbers()
+
+
+
+ function testBooleans()
+ {
+ $n3 = '@prefix : <http://example.org/#> .
+ :foo :bar @true .
+ :foo :bar @false .
+ ';
+ $parser = &new N3Parser();
+ //$parser->debug = true;
+ $model = &$parser->parse2model($n3, false);
+
+ $model2 = new MemModel();
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(true, null, XML_SCHEMA . 'boolean')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#foo"),
+ new Resource("http://example.org/#bar"),
+ new Literal(false, null, XML_SCHEMA . 'boolean')
+ )
+ );
+
+ //var_dump($model->triples);
+ $this->assertEqual(2, $model->size());
+ $this->assertTrue($model->containsAll($model2));
+ }//function testBooleans()
+}
?>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 06:44:39
|
Revision: 501
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=501&view=rev
Author: cweiske
Date: 2007-08-12 23:44:36 -0700 (Sun, 12 Aug 2007)
Log Message:
-----------
Add single quote support to N3 parser, along with unit tests
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Parser.php
trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Parser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-13 06:14:37 UTC (rev 500)
+++ trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-13 06:44:36 UTC (rev 501)
@@ -76,7 +76,12 @@
$bNode = '_:'.$Name;
$Univar = '\?'.$Name;
$QName = '(?:[A-Za-z][A-Za-z0-9_@\.]*)?:'.$Name;
- $Literal = '"(\\\"|[^"])*"'; # '"(?:\\"|[^"])*"'
+ $Literal = '(?:'
+ . '"(\\\"|[^"])*"'
+ . '|'
+ . "'(\\\'|[^'])*'"
+ . ')';
+ # '"(?:\\"|[^"])*"'
$Number = '[-+]?[0-9]+(\\.[0-9]+)?([eE][-+]?[0-9]+)?';
$Boolean = '@(?:true|false)';
// $Literal = '"[^"\\\\]*(?:\\.\\[^"\\]*)*"'; # '"(?:\\"|[^"])*"'
@@ -84,7 +89,11 @@
$Datatype = '(\^\^)[^ ,\.;)]+';
$Datatype_URI = '(\^\^)'.$URI;
// $LLiteral = '"""[^"\\\\]*(?:(?:.|"(?!""))[^"\\\\]*)*"""';
- $LLiteral = '"""[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""';
+ $LLiteral = '(?:'
+ . '"""[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
+ . '|'
+ . "'''[^'\\\\]*(?:(?:\\\\.|'(?!''))[^\"\\\\]*)*'''"
+ . ')';
// '"""[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
$Comment = '#.*$';
$Prefix = '(?:[A-Za-z][A-Za-z0-9_]*)?:';
@@ -576,7 +585,7 @@
//float or decimal
// After conversion we cannot distinguish between both
$list[$i] = floatval($list[$i]);
- } else if ((!strstr('<_"?.;,{}[]()@', $list[$i]{0}))
+ } else if ((!strstr('<_"\'?.;,{}[]()@', $list[$i]{0}))
&& (substr($list[$i],0,3) != '^^<')
) {
//prefix or unknown
@@ -596,16 +605,28 @@
}
} else {
- if ($list[$i]{0} == '"') { // Congratulations - it's a literal!
- if (substr($list[$i],0,3) == '"""') {
- if (substr($list[$i],-3,3) == '"""') { // A big literal...
+ if ($list[$i]{0} == '"') {
+ $bLiteral = true;
+ $chBase = '"';
+ } else if ($list[$i]{0} == '\'') {
+ $bLiteral = true;
+ $chBase = '\'';
+ } else {
+ $bLiteral = false;
+ }
+ if ($bLiteral) {
+ $tripleBase = $chBase . $chBase . $chBase;
+ // Congratulations - it's a literal!
+ if (substr($list[$i], 0, 3) == $tripleBase) {
+ if (substr($list[$i],-3,3) == $tripleBase) {
+ // A big literal...
$lit = substr($list[$i],3,-3);
// print "++$lit++";
$lit=str_replace('\n', '\\n',$lit);
- $lit=ereg_replace("[^\\]\"", "\\\"", $lit);
+ $lit=ereg_replace("[^\\]" . $chBase, "\\" . $chBase, $lit);
- $list[$i] = '"'.$lit.'"';
+ $list[$i] = $chBase . $lit . $chBase;
} else {
die ('Incorrect string formatting: '.substr($list[$i],-3,3));
}
@@ -1044,7 +1065,7 @@
function toRDFNode($s, $state)
{
$ins = substr($s, 1, -1);
- if ($s{0} == '"') {
+ if ($s{0} == '"' || $s{0} == '\'') {
$lang = NULL;
if (count($state)>3) {
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-13 06:14:37 UTC (rev 500)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Parser_test.php 2007-08-13 06:44:36 UTC (rev 501)
@@ -37,16 +37,21 @@
}
- function testIsMemmodel() {
+
+
+ function testIsMemmodel()
+ {
// Import Package
$n3pars= new N3Parser();
$model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
$this->assertIsA($model, 'memmodel');
}
- function testParsing() {
+
+ function testParsing()
+ {
$n3pars= new N3Parser();
$model=$n3pars->parse2model($_SESSION['n3TestInput'],false);
@@ -77,7 +82,62 @@
$this->assertTrue($model->containsAll($model2));
}
- function testPrefixNotDeclared() {
+
+
+ /**
+ * Test different string quotation methods
+ */
+ function testQuotes()
+ {
+ $n3 = <<<EOT
+@prefix : <http://example.org/#> .
+
+# This file uses UNIX line end conventions.
+
+:x1 :p1 'x' .
+:x2 :p2 '''x
+y''' .
+
+:x3 :p3 """x
+y"""^^:someType .
+
+
+EOT;
+ $parser = &new N3Parser();
+ $model = &$parser->parse2model($n3, false);
+
+ $model2 = new MemModel();
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#x1"),
+ new Resource("http://example.org/#p1"),
+ new Literal('x')
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#x2"),
+ new Resource("http://example.org/#p2"),
+ new Literal("x\ny")
+ )
+ );
+ $model2->add(
+ new Statement(
+ new Resource("http://example.org/#x3"),
+ new Resource("http://example.org/#p3"),
+ new Literal("x\ny", null, 'http://example.org/#someType')
+ )
+ );
+
+ //var_dump($model->triples, $model2->triples);
+ $this->assertEqual(3, $model->size());
+ $this->assertTrue($model->containsAll($model2));
+ }//function testQuotes()
+
+
+
+ function testPrefixNotDeclared()
+ {
$rdfInput='
@prefix m: <http://www.example.org/meeting_organization#>.
@@ -93,7 +153,10 @@
$this->assertErrorPattern('[Prefix not declared: p:]');
}
- function testLoneSemicolon() {
+
+
+ function testLoneSemicolon()
+ {
$n3 = '<a> <b> <c> ; .';
$parser = &new N3Parser();
$model = &$parser->parse2model($n3, false);
@@ -101,7 +164,10 @@
$this->assertNoErrors();
}
- function testTightClosingList() {
+
+
+ function testTightClosingList()
+ {
$n3 = '@prefix : <http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql4/manifest#> .
@prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
<> mf:entries ( mf:syn-09) .';
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 13:51:50
|
Revision: 512
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=512&view=rev
Author: cweiske
Date: 2007-08-13 06:51:30 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
- Add SimpleTest EARL [1] renderer
- Add nesting option to N3Serializer so that we get
[ x:a x:b [ x:c [x:d x:e]]] now
[1] http://www.w3.org/2001/sw/DataAccess/tests/earl
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Serializer.php
trunk/rdfapi-php/test/config.php.dist
trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php
trunk/rdfapi-php/test/unit/sparqlParserTests.php
Added Paths:
-----------
trunk/rdfapi-php/test/unit/EarlReporter.php
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 11:58:24 UTC (rev 511)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 13:51:30 UTC (rev 512)
@@ -36,7 +36,8 @@
var $debug = false;
- var $prefixes;
+ var $prefixes = array();
+ var $noPrefixes = array();
var $done; // keeps track of already serialized resources
var $resourcetext;
@@ -47,6 +48,7 @@
var $styleCompress = false;
var $stylePretty = false;
+ var $styleNest = false;
/**
* Constructor
@@ -66,9 +68,9 @@
* @param string $s
* @returns void
**/
- function addNSPrefix( $ns, $prefix)
+ function addNSPrefix($ns, $prefix)
{
- $this->prefixes[$ns]=$prefix;
+ $this->prefixes[$ns] = $prefix;
}
@@ -81,14 +83,38 @@
$this->prefixes = array();
}
+
+
/**
+ * Add a namespace that shall not get shortened by using a prefix.
+ *
+ * @param string $ns Namespace URI like "http://example.com/"
+ */
+ function addNoNSPrefix($ns)
+ {
+ $this->noPrefixes[$ns] = true;
+ }
+
+
+
+ /**
+ * Clears all previously set noNamespace prefixes
+ */
+ function clearNoNSPrefixes()
+ {
+ $this->noPrefixes = array();
+ }
+
+
+
+ /**
* Serializes a model to N3 syntax.
*
* @param object Model $model
* @return string
* @access public
*/
- function & serialize(&$m)
+ function &serialize(&$m)
{
if (is_a($m, 'DbModel')) {
$m=$m->getMemModel();
@@ -111,9 +137,9 @@
}
}
- $namespaces =array();
- $count =array();
- $resources =array();
+ $namespaces = array();
+ $count = array();
+ $resources = array();
foreach ($this->model->triples as $t) {
$s = $t->getSubject();
if (is_a($s, 'Resource')) {
@@ -127,14 +153,20 @@
if (is_a($o, 'Resource')) {
$namespaces[$o->getNamespace()] = 1;
}
- $uri=$s->getURI();
+ $uri = $s->getURI();
if (isset($count[$uri])) {
$count[$uri]++;
} else {
- $count[$uri]=0;
- $resources[$uri]=$s;
+ $count[$uri] = 0;
+ $resources[$uri] = $s;
}
+
+ if ($this->styleNest && is_a($s, 'BlankNode')) {
+ //make sure blank nodes are sorted *after* normal nodes
+ //so that they can be included
+ $count[$uri] -= 0.00001;
+ }
}
if (!HIDE_ADVERTISE) {
@@ -155,11 +187,11 @@
}
$c = 0;
- foreach ( $this->resourcetext as $r=>$t) {
- if ( preg_match_all('/'.MAGIC_STRING.'([^ ]+)'.MAGIC_STRING.'/', $t, $ms, PREG_SET_ORDER)) {
- foreach($ms as $mseach) {
- $rp=$this->resourcetext[$mseach[1]];
- $t=preg_replace('/'.MAGIC_STRING.$mseach[1].MAGIC_STRING.'/', $rp, $t);
+ foreach ($this->resourcetext as $r => $t) {
+ if (preg_match_all('/'.MAGIC_STRING.'([^ ]+)'.MAGIC_STRING.'/', $t, $ms, PREG_SET_ORDER)) {
+ foreach ($ms as $mseach) {
+ $rp = $this->resourcetext[$mseach[1]];
+ $t = preg_replace('/'.MAGIC_STRING.$mseach[1].MAGIC_STRING.'/', $rp, $t);
}
}
@@ -188,7 +220,7 @@
// }
return $this->res;
- }
+ }//function &serialize(&$m)
@@ -201,7 +233,7 @@
* @return boolean
* @access public
*/
- function saveAs(&$model, $filename)
+ function saveAs(&$model, $filename)
{
// serialize model
$n3 = $this->serialize($model);
@@ -217,6 +249,8 @@
};
}
+
+
/**
* Set to true, if the N3 serializer should try to compress the blank node
* syntax using [] whereever possible.
@@ -236,6 +270,17 @@
$this->stylePretty = $prettyPrint;
}
+
+
+ /**
+ * Enables nesting of blank nodes with [] if
+ * compression is activated via @see setCompress
+ */
+ function setNest($nest)
+ {
+ $this->styleNest = $nest;
+ }
+
/* ==================== Private Methods from here ==================== */
@@ -247,14 +292,16 @@
**/
function reset()
{
- $this->anon=0;
- $this->done=array();
- $this->resourcetext_taken=array();
- $this->resourcetext=array();
- $this->res='';
- $this->model=NULL;
+ $this->anon = 0;
+ $this->done = array();
+ $this->resourcetext_taken = array();
+ $this->resourcetext = array();
+ $this->res = '';
+ $this->model = null;
}
+
+
/**
* Makes ns0, ns1 etc. prefixes for unknown prefixes.
* Outputs @prefix lines.
@@ -266,11 +313,11 @@
{
$c = 0;
foreach ($n as $ns => $nonsense) {
- if (!$ns) {
+ if (!$ns || isset($this->noPrefixes[$ns])) {
continue;
}
if (isset($this->prefixes[$ns])) {
- $p=$this->prefixes[$ns];
+ $p = $this->prefixes[$ns];
} else {
$p = 'ns' . $c;
$this->prefixes[$ns] = $p;
@@ -280,29 +327,31 @@
}
}
+
+
/**
* Fill in $resourcetext for a single resource.
* Will recurse into Objects of triples, but should never look ? (really?)
- * @access private
* @param object Resource $r
* @returns boolean
+ * @access private
**/
- function doResource(&$r)
+ function doResource(&$r, $bEmbedded = false, $strIndent = ' ')
{
- // print $r->getURI();
+ //var_dump($r->getURI());
- $ts=$this->model->find($r, null, null);
- if (count($ts->triples)==0) {
+ $ts = $this->model->find($r, null, null);
+ if (count($ts->triples) == 0) {
return;
}
$out = '';
if (isset($this->done[$r->getURI()]) && $this->done[$r->getURI()]) {
- if (is_a($r, 'BlankNode')) {
+ if (!$this->styleNest && is_a($r, 'BlankNode')) {
if ($this->resourcetext_taken[$r->getURI()] == 1) {
//Oh bother, we must use the _:blah construct.
- $a=$this->resourcetext[$r->getURI()];
+ $a = $this->resourcetext[$r->getURI()];
$this->resourcetext[$r->getURI()]='_:anon'.$this->anon;
$this->resourcetext['_:anon'.$this->anon]=$this->fixAnon($a, '_:anon'.$this->anon);
$this->resourcetext_taken[$r->getURI()]=2;
@@ -319,7 +368,11 @@
if (is_a($r, 'BlankNode')) {
//test, if this blanknode is referenced somewhere
$rbn = $this->model->find(null, null, $r);
- $compress = count($rbn->triples) == 0 && (N3SER_BNODE_SHORT || $this->styleCompress);
+ $compress = (N3SER_BNODE_SHORT || $this->styleCompress)
+ && (
+ count($rbn->triples) == 0
+ || (count($rbn->triples) == 1 && $bEmbedded)
+ );
if ($compress) {
$out.='[';
} else {
@@ -335,14 +388,14 @@
$out .= ' ';
foreach ($ts->triples as $t) {
- $p=$t->getPredicate();
+ $p = $t->getPredicate();
if ($p == $lastp) {
- $out.=' , ';
+ $out .= ' , ';
} else {
if ($lastp!='') {
if ($this->stylePretty) {
- $out .= ";\n ";
+ $out .= ";\n" . $strIndent;
} else {
$out .= ' ; ';
}
@@ -374,11 +427,15 @@
if ($this->debug) {
print 'Doing object: '.$o->getURI().LINEFEED;
}
- if (is_a($o,'BlankNode')) {
- // $this->doResource($o);
- // $out.=MAGIC_STRING.$o->getURI().MAGIC_STRING; #$this->resourcetext[$o->getURI()];
- // $this->resourcetext_taken[$o->getURI()]=1;
- $out .= '_:'.$o->getLabel();
+ if (is_a($o, 'BlankNode')) {
+ if ($this->styleNest) {
+ $this->doResource($o, true, $strIndent . ' ');
+ $out .= MAGIC_STRING . $o->getURI() . MAGIC_STRING;
+ //$out .= $this->resourcetext[$o->getURI()];
+ $this->resourcetext_taken[$o->getURI()] = 1;
+ } else {
+ $out .= '_:'.$o->getLabel();
+ }
} else {
$this->doURI($o, $out);
}
@@ -399,8 +456,8 @@
/**
* Format a single URI
* @param string $s
+ * @return void
* @access private
- * @return void
**/
function doURI(&$r, &$out)
{
@@ -408,11 +465,12 @@
$out .= 'a';
return;
}
- if ($r->getNamespace()!='') {
- $out .= $this->prefixes[$r->getNamespace()].':'.$r->getLocalName();
+ $ns = $r->getNamespace();
+ if ($ns != '' && !isset($this->noPrefixes[$ns])) {
+ $out .= $this->prefixes[$ns].':'.$r->getLocalName();
} else {
- //Will this ever happen?
- $out .= $r->getURI();
+ //Will this ever happen? It does, now.
+ $out .= '<' . $r->getURI() . '>';
}
}
@@ -427,9 +485,8 @@
**/
function fixAnon($t,$a)
{
- $t=preg_replace("/( \] $|^\[ )/", '', $t);
-
- return $a.$t;
+ $t = preg_replace("/( \] $|^\[ )/", '', $t);
+ return $a . $t;
}
}
Modified: trunk/rdfapi-php/test/config.php.dist
===================================================================
--- trunk/rdfapi-php/test/config.php.dist 2007-08-13 11:58:24 UTC (rev 511)
+++ trunk/rdfapi-php/test/config.php.dist 2007-08-13 13:51:30 UTC (rev 512)
@@ -18,8 +18,17 @@
'password' => ''
);
-//enable this to get more informatin about failing unit tests
+//enable this to get more information about failing unit tests
//$GLOBALS['debugTests'] = true;
+//used in W3C earl report serialization
+$GLOBALS['earlReport'] = array(
+ 'reporter' => array(
+ 'name' => 'John Doe',
+ 'seeAlso' => 'http://example.org/john/johndoe.rdf',
+ 'homepage' => 'http://example.org/john/'
+ )
+);
+
define('LOG', false);
?>
\ No newline at end of file
Added: trunk/rdfapi-php/test/unit/EarlReporter.php
===================================================================
--- trunk/rdfapi-php/test/unit/EarlReporter.php (rev 0)
+++ trunk/rdfapi-php/test/unit/EarlReporter.php 2007-08-13 13:51:30 UTC (rev 512)
@@ -0,0 +1,231 @@
+<?php
+/**
+* EARL reporter for SimpleTest
+*
+* @author Christian Weiske <cw...@cw...>
+* @see http://www.w3.org/2001/sw/DataAccess/tests/earl
+*/
+require_once SIMPLETEST_INCLUDE_DIR . 'simpletest.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
+require_once RDFAPI_INCLUDE_DIR . 'syntax/N3Serializer.php';
+
+
+class EarlReporter extends SimpleReporter
+{
+ const EARL = 'http://www.w3.org/ns/earl#';
+ const FOAF = 'http://xmlns.com/foaf/0.1/';
+ const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
+ const RDFS = 'http://www.w3.org/2000/01/rdf-schema#';
+ const DOAP = 'http://usefulinc.com/ns/doap#';
+
+ protected $model = null;
+ protected $serializer = null;
+
+ /**
+ * Set via $testcase->signal('earl:test', 'mytestname')
+ */
+ protected $currentTestName = null;
+
+
+
+ public function __construct($serializer = null, $model = null)
+ {
+ if ($serializer !== null) {
+ $this->serializer = $serializer;
+ } else {
+ $this->serializer = new N3Serializer();
+ }
+
+ if ($model !== null) {
+ $this->model = model;
+ } else {
+ $this->model = new MemModel();
+ }
+
+ if (!isset($GLOBALS['earlReport'])) {
+ die('Please configure $GLOBALS[\'earlReport\'] as shown in config.php.dist' . "\n");
+ }
+ }//public function __construct($serializer = null, $model = null)
+
+
+
+ function paintHeader($test_name)
+ {
+ //add personal information about the asserter
+ $this->assertingPerson = new Resource($GLOBALS['earlReport']['reporter']['seeAlso'] . '#me');
+ $this->model->add(new Statement(
+ $this->assertingPerson,
+ new Resource(self::RDF . 'type'),
+ new Resource(self::FOAF . 'Person')
+ ));
+ $this->model->add(new Statement(
+ $this->assertingPerson,
+ new Resource(self::RDFS . 'seeAlso'),
+ new Resource($GLOBALS['earlReport']['reporter']['seeAlso'])
+ ));
+ $this->model->add(new Statement(
+ $this->assertingPerson,
+ new Resource(self::FOAF . 'homepage'),
+ new Resource($GLOBALS['earlReport']['reporter']['homepage'])
+ ));
+ $this->model->add(new Statement(
+ $this->assertingPerson,
+ new Resource(self::FOAF . 'name'),
+ new Literal($GLOBALS['earlReport']['reporter']['name'])
+ ));
+
+
+ //project information
+ $this->project = new Resource('http://rdfapi-php.sf.net/');
+ $this->model->add(new Statement(
+ $this->project,
+ new Resource(self::RDF . 'type'),
+ new Resource(self::DOAP . 'Project')
+ ));
+ $this->model->add(new Statement(
+ $this->project,
+ new Resource(self::DOAP . 'name'),
+ new Literal('RDF API for PHP')
+ ));
+ $version = new BlankNode($this->model);
+ $this->model->add(new Statement(
+ $this->project,
+ new Resource(self::DOAP . 'release'),
+ $version
+ ));
+ $this->model->add(new Statement(
+ $version,
+ new Resource(self::RDF . 'type'),
+ new Resource(self::DOAP . 'Version')
+ ));
+ $this->model->add(new Statement(
+ $version,
+ new Resource(self::DOAP . 'created'),
+ new Literal(date('Y-m-d H:i'), null, 'http://www.w3.org/2001/XMLSchema#date')
+ ));
+ $this->model->add(new Statement(
+ $version,
+ new Resource(self::DOAP . 'name'),
+ new Literal('RAP SVN-' . date('Y-m-d\\TH:i'))
+ ));
+ }//function paintHeader($test_name)
+
+
+
+ function paintFooter($test_name)
+ {
+ $this->serializer->addNSPrefix(self::DOAP, 'doap');
+ $this->serializer->addNSPrefix(self::EARL, 'earl');
+ $this->serializer->addNSPrefix(self::FOAF, 'foaf');
+
+ $this->serializer->addNoNSPrefix('http://rdfapi-php.sf.net/');
+ $this->serializer->addNoNSPrefix($GLOBALS['earlReport']['reporter']['homepage']);
+
+ $this->serializer->setCompress(true);
+ $this->serializer->setPrettyPrint(true);
+ $this->serializer->setNest(true);
+
+ echo $this->serializer->serialize(
+ $this->model
+ );
+ }
+
+
+
+ /**
+ * We use this to keep track of test titles
+ */
+ function paintSignal($type, $payload)
+ {
+ switch ($type) {
+ case 'earl:name':
+ $this->currentTestName = $payload;
+ break;
+ default:
+ echo "Unknown signal type $type\n";
+ break;
+ }
+ }//function paintSignal($type, $payload)
+
+
+ function paintStart($test_name, $size) {
+ parent::paintStart($test_name, $size);
+ }
+
+ function paintEnd($test_name, $size) {
+ parent::paintEnd($test_name, $size);
+ }
+
+ function paintPass($message) {
+ $this->addTest(true);
+// echo 'pass: ' . $message . "\n";
+ parent::paintPass($message);
+ }
+
+ function paintFail($message) {
+ $this->addTest(false);
+// echo 'fail: ' . $message . "\n";
+ parent::paintFail($message);
+ }
+
+ function addTest($bPass)
+ {
+ if ($this->currentTestName === null) {
+// echo "No test name set! Ignoring test\n";
+ return;
+ }
+
+ $assertion = new BlankNode($this->model);
+ $this->model->add(new Statement(
+ $assertion,
+ new Resource(self::RDF . 'type'),
+ new Resource(self::EARL . 'Assertion')
+ ));
+ $this->model->add(new Statement(
+ $assertion,
+ new Resource(self::EARL . 'assertedBy'),
+ $this->assertingPerson
+ ));
+
+ $result = new BlankNode($this->model);
+ $this->model->add(new Statement(
+ $assertion,
+ new Resource(self::EARL . 'result'),
+ $result
+ ));
+ $this->model->add(new Statement(
+ $result,
+ new Resource(self::RDF . 'type'),
+ new Resource(self::EARL . 'TestResult')
+ ));
+ $this->model->add(new Statement(
+ $result,
+ new Resource(self::EARL . 'outcome'),
+ new Resource(self::EARL . ($bPass ? 'pass' : 'fail'))
+ ));
+ $this->model->add(new Statement(
+ $assertion,
+ new Resource(self::EARL . 'subject'),
+ $this->project
+ ));
+ $this->model->add(new Statement(
+ $assertion,
+ new Resource(self::EARL . 'test'),
+ new Resource($this->currentTestName)
+ ));
+
+/*
+ [ a earl:Assertion;
+ earl:assertedBy _8:chime;
+ earl:result [ a earl:TestResult;
+ earl:outcome earl:pass];
+ earl:subject <http://rdflib.net>;
+ earl:test _7:dawg-graph-02].
+*/
+
+ $this->currentTestName = null;
+ }//function addTest($bPass)
+
+}//class EarlReporter extends SimpleReporter
+
+?>
\ No newline at end of file
Modified: trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php 2007-08-13 11:58:24 UTC (rev 511)
+++ trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php 2007-08-13 13:51:30 UTC (rev 512)
@@ -97,7 +97,7 @@
function testParseFilter()
{
- echo "<b>FilterParser tests</b><br/>\n";
+ //echo "<b>FilterParser tests</b><br/>\n";
foreach ($GLOBALS['testSparqlParserTestsFilter'] as $arFilterTest) {
list($query, $result) = $arFilterTest;
@@ -122,7 +122,7 @@
function testParseNested()
{
- echo "<b>Nested queries tests</b><br/>\n";
+ //echo "<b>Nested queries tests</b><br/>\n";
foreach ($GLOBALS['testSparqlParserTestsNested'] as $arNestedTest) {
list($query, $strExpected) = $arNestedTest;
@@ -162,10 +162,13 @@
}
continue;
}
+ $this->signal('earl:name', $test['title']);
$qs = file_get_contents(SPARQL_TESTFILES . $test['query']);
$this->runQueryParseTest($qs, $parser, $test['type'], $test['title']);
+
+ //++$nCount; if ($nCount > 2) break;
}
}//function testDawg2SyntaxTests()
Modified: trunk/rdfapi-php/test/unit/sparqlParserTests.php
===================================================================
--- trunk/rdfapi-php/test/unit/sparqlParserTests.php 2007-08-13 11:58:24 UTC (rev 511)
+++ trunk/rdfapi-php/test/unit/sparqlParserTests.php 2007-08-13 13:51:30 UTC (rev 512)
@@ -4,9 +4,10 @@
die('Make a copy of test/config.php.dist, change it and save it as test/config.php');
}
-require_once( SIMPLETEST_INCLUDE_DIR . 'unit_tester.php');
-require_once( SIMPLETEST_INCLUDE_DIR . 'reporter.php');
-require_once('show_passes.php');
+require_once SIMPLETEST_INCLUDE_DIR . 'unit_tester.php';
+require_once SIMPLETEST_INCLUDE_DIR . 'reporter.php';
+require_once dirname(__FILE__) . '/EarlReporter.php';
+require_once 'show_passes.php';
require(RDFAPI_INCLUDE_DIR . 'RdfAPI.php');
$_SESSION['passes'] = 0;
@@ -22,6 +23,7 @@
$test_sparql->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Sparql/SparqlParserTests_test.php');
//$test_sparql->run(new ShowPasses());
$test_sparql->run(new TextReporter());
+//$test_sparql->run(new EarlReporter());
if(LOG){
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 15:43:38
|
Revision: 515
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=515&view=rev
Author: cweiske
Date: 2007-08-13 08:43:35 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
This is why we need unit tests
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Serializer.php
Added Paths:
-----------
trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 15:17:42 UTC (rev 514)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 15:43:35 UTC (rev 515)
@@ -199,7 +199,7 @@
$this->res .= $c . ': ';
}
if (!(isset($this->resourcetext_taken[$r]) && $this->resourcetext_taken[$r]>0)) {
- $this->res .= $t . '.' . LINEFEED;
+ $this->res .= $t . ' .' . LINEFEED;
if ($this->stylePretty) {
$this->res .= LINEFEED;
}
Added: trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php (rev 0)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 15:43:35 UTC (rev 515)
@@ -0,0 +1,48 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
+require_once RDFAPI_INCLUDE_DIR . 'syntax/N3Serializer.php';
+require_once RDFAPI_INCLUDE_DIR . 'syntax/N3Parser.php';
+
+/**
+ * Unit tests for N3Serializer
+ *
+ * @version $Id$
+ * @author Christian Weiske <cw...@cw...>
+ *
+ * @package unittests
+ */
+class testN3SerializerTests extends UnitTestCase
+{
+ function testSimple()
+ {
+ $mod = new MemModel();
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Resource("mailto:fr...@ex..."))
+ );
+
+ $ser = new N3Serializer();
+ $str = $ser->serialize($mod);
+
+ $this->assertTrue(strpos($str, '<http://example.org/>') > 0);
+ $this->assertTrue(strpos($str, '@prefix') !== false);
+ $this->assertTrue(strpos($str, ':foo') > 0);
+ $this->assertTrue(strpos($str, ':bar') > 0);
+ $this->assertTrue(strpos($str, 'fr...@ex...') > 0);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+ $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
+ $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ }//function testSimple()
+
+
+
+
+ }
+?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 16:14:22
|
Revision: 517
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=517&view=rev
Author: cweiske
Date: 2007-08-13 09:14:17 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
Fix N3Parser to unescape quotes
More tests
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Parser.php
trunk/rdfapi-php/api/syntax/N3Serializer.php
trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Parser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-13 15:59:46 UTC (rev 516)
+++ trunk/rdfapi-php/api/syntax/N3Parser.php 2007-08-13 16:14:17 UTC (rev 517)
@@ -624,7 +624,8 @@
// print "++$lit++";
$lit=str_replace('\n', '\\n',$lit);
- $lit=ereg_replace("[^\\]" . $chBase, "\\" . $chBase, $lit);
+ //$lit=ereg_replace("[^\\]" . $chBase, "\\" . $chBase, $lit);
+ $lit = stripslashes($lit);
$list[$i] = $chBase . $lit . $chBase;
} else {
@@ -632,8 +633,9 @@
}
} else {
if (strstr($list[$i],"\n")) {
- die('Newline in literal: '+$list[$i]);
+ die('Newline in literal: ' . $list[$i]);
}
+ $list[$i] = stripslashes($list[$i]);
}
}
}
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 15:59:46 UTC (rev 516)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 16:14:17 UTC (rev 517)
@@ -423,10 +423,13 @@
$quoteChar = $long ? '"""' : '"';
} else if ($quoteDouble && !$quoteSingle) {
$quoteChar = $long ? '\'\'\'' : '\'';
- } else {
+ } else if ($quoteDouble && $quoteSingle) {
//both quotation chars inside
$quoteChar = $long ? '"""' : '"';
$l = addslashes($l);
+ } else {
+ //no quotation chars
+ $quoteChar = $long ? '"""' : '"';
}
$out .= $quoteChar . $l . $quoteChar;
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 15:59:46 UTC (rev 516)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 16:14:17 UTC (rev 517)
@@ -19,8 +19,8 @@
$mod->add(new Statement(
new Resource("http://example.org/foo"),
new Resource("http://example.org/bar"),
- new Resource("mailto:fr...@ex..."))
- );
+ new Resource("mailto:fr...@ex...")
+ ));
$ser = new N3Serializer();
$str = $ser->serialize($mod);
@@ -43,6 +43,92 @@
+ function testStringsSimple()
+ {
+ $mod = new MemModel();
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal('testliteral')
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test''literal")
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test\"\"literal")
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test\nliteral")
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test\"\nliteral")
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test'\nliteral")
+ ));
+
+ $ser = new N3Serializer();
+ $str = $ser->serialize($mod);
+
+ $this->assertTrue(strpos($str, 'testliteral') > 0);
+ $this->assertTrue(strpos($str, "test''literal") > 0);
+ $this->assertTrue(strpos($str, 'test""literal') > 0);
+ $this->assertTrue(strpos($str, "test\nliteral") > 0);
+ $this->assertTrue(strpos($str, "'''test\"\nliteral'''") > 0);
+ $this->assertTrue(strpos($str, '"""test\'' . "\n" . 'literal"""') > 0);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+ $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
+ $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ }
+
+
+ function testStringsAdvanced()
+ {
+ $mod = new MemModel();
+ //up to now, we didn't trick the serializer
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test'\"literal")
+ ));
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ new Literal("test'\"\nliteral")
+ ));
+
+
+ $ser = new N3Serializer();
+ $str = $ser->serialize($mod);
+
+ $this->assertTrue(strpos($str, 'test\\\'\\"literal') > 0);
+ $this->assertTrue(strpos($str, 'test\\\'\\"' . "\n" . 'literal') > 0);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+ $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
+ $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ }
}
?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 17:26:51
|
Revision: 519
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=519&view=rev
Author: cweiske
Date: 2007-08-13 10:26:48 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
Fix bug when nesting blank node at the end
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Serializer.php
trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 16:35:51 UTC (rev 518)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 17:26:48 UTC (rev 519)
@@ -342,6 +342,9 @@
$ts = $this->model->find($r, null, null);
if (count($ts->triples) == 0) {
+ if ($bEmbedded) {
+ $this->resourcetext[$r->getURI()] = '_:' . $r->getLabel();
+ }
return;
}
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 16:35:51 UTC (rev 518)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 17:26:48 UTC (rev 519)
@@ -193,5 +193,200 @@
$this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
}
- }
+
+
+ function testCompressOneBlank()
+ {
+ $mod = new MemModel();
+ $b1 = new BlankNode($mod);
+ $mod->add(new Statement(
+ $b1,
+ new Resource("http://example.org/bar1"),
+ new Literal('baz')
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+ //var_dump($str);//, $mod2->triples);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+
+ $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+ $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
+ $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ }
+
+
+
+ function testCompressTwoBlanks()
+ {
+ $mod = new MemModel();
+ $b1 = new BlankNode($mod);
+ $b2 = new BlankNode($mod);
+ $mod->add(new Statement(
+ $b1,
+ new Resource("http://example.org/bar1"),
+ new Literal('baz1')
+ ));
+ $mod->add(new Statement(
+ $b2,
+ new Resource("http://example.org/bar2"),
+ new Literal('baz2')
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
+ }
+
+
+
+ function testCompressBlankAtEnd()
+ {
+ $mod = new MemModel();
+ $b3 = new BlankNode($mod);
+ $mod->add(new Statement(
+ new Resource('http://example.org/foo'),
+ new Resource("http://example.org/bar2"),
+ $b3
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
+ }
+
+
+
+ function testNest()
+ {return;
+ $mod = new MemModel();
+ $b100 = new BlankNode($mod);
+ $b110 = new BlankNode($mod);
+ $b120 = new BlankNode($mod);
+ $b111 = new BlankNode($mod);
+ $mod->add(new Statement(
+ new Resource("http://example.org/foo"),
+ new Resource("http://example.org/bar"),
+ $b100
+ ));
+ $mod->add(new Statement(
+ $b100,
+ new Resource("http://example.org/bar2"),
+ $b110
+ ));
+ $mod->add(new Statement(
+ $b110,
+ new Resource("http://example.org/bar4"),
+ $b111
+ ));
+ $mod->add(new Statement(
+ $b100,
+ new Resource("http://example.org/bar3"),
+ $b120
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ var_dump($str);//, $mod2->triples);
+
+ $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+ $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
+ $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ }
+
+
+
+ function testNestBlankAtEnd()
+ {
+ $mod = new MemModel();
+ $b3 = new BlankNode($mod);
+ $mod->add(new Statement(
+ new Resource('http://example.org/foo'),
+ new Resource("http://example.org/bar2"),
+ $b3
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
+ }
+
+
+
+
+
+
+
+
+
+ function compareModelsIgnoringBlankNodes($mod1, $mod2)
+ {
+ $this->assertEqual($mod1->size(), $mod2->size(), 'Original model size and loaded model size should equal');
+
+ foreach ($mod1->triples as &$triple) {
+ $s = $p = $o = null;
+ if (!$triple->subj instanceof BlankNode) {
+ $s = $triple->subj;
+ }
+ if (!$triple->pred instanceof BlankNode) {
+ $p = $triple->pred;
+ }
+ if (!$triple->obj instanceof BlankNode) {
+ $o = $triple->obj;
+ }
+ $res = $mod2->find($s, $p, $o);
+ $this->assertTrue($res->size() > 0);
+ }
+
+ foreach ($mod2->triples as &$triple) {
+ $s = $p = $o = null;
+ if (!$triple->subj instanceof BlankNode) {
+ $s = $triple->subj;
+ }
+ if (!$triple->pred instanceof BlankNode) {
+ $p = $triple->pred;
+ }
+ if (!$triple->obj instanceof BlankNode) {
+ $o = $triple->obj;
+ }
+ $res = $mod1->find($s, $p, $o);
+ $this->assertTrue($res->size() > 0);
+ }
+ }//function compareModelsIgnoringBlankNodes($mod1, $mod2)
+
+}
?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 17:52:01
|
Revision: 520
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=520&view=rev
Author: cweiske
Date: 2007-08-13 10:51:59 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
Squash another bug in nesting code
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Serializer.php
trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 17:26:48 UTC (rev 519)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 17:51:59 UTC (rev 520)
@@ -369,7 +369,7 @@
if (is_a($r, 'Resource')) {
if (is_a($r, 'BlankNode')) {
- //test, if this blanknode is referenced somewhere
+ //test if this blanknode is referenced somewhere
$rbn = $this->model->find(null, null, $r);
$compress = (N3SER_BNODE_SHORT || $this->styleCompress)
&& (
@@ -449,7 +449,9 @@
print 'Doing object: '.$o->getURI().LINEFEED;
}
if (is_a($o, 'BlankNode')) {
- if ($this->styleNest) {
+ if ($this->styleNest && $this->styleCompress
+ && !isset($this->done[$o->getURI()])
+ ) {
$this->doResource($o, true, $strIndent . ' ');
$out .= MAGIC_STRING . $o->getURI() . MAGIC_STRING;
//$out .= $this->resourcetext[$o->getURI()];
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 17:26:48 UTC (rev 519)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 17:51:59 UTC (rev 520)
@@ -277,6 +277,67 @@
+ function testNestSimple()
+ {
+ $mod = new MemModel();
+ $b3 = new BlankNode($mod);
+ $mod->add(new Statement(
+ new Resource('http://example.org/foo'),
+ new Resource("http://example.org/bar2"),
+ $b3
+ ));
+ $mod->add(new Statement(
+ $b3,
+ new Resource("http://example.org/bar2"),
+ new Literal('hohoho')
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str, $mod2->triples);
+
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
+ }
+
+
+
+ function testNestSimpleBlankStart()
+ {
+ $mod = new MemModel();
+ $b1 = new BlankNode($mod);
+ $b3 = new BlankNode($mod);
+ $mod->add(new Statement(
+ $b1,
+ new Resource("http://example.org/bar2"),
+ $b3
+ ));
+ $mod->add(new Statement(
+ $b3,
+ new Resource("http://example.org/bar2"),
+ new Literal('hohoho')
+ ));
+
+ $ser = new N3Serializer();
+ $ser->setCompress(true);
+ $ser->setNest(true);
+ $str = $ser->serialize($mod);
+
+ //test if it can be loaded
+ $par = new N3Parser();
+ $mod2 = $par->parse2model($str, false);
+ //var_dump($str);//, $mod2->triples);
+
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
+ }
+
+
+
function testNest()
{return;
$mod = new MemModel();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-13 18:05:11
|
Revision: 521
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=521&view=rev
Author: cweiske
Date: 2007-08-13 11:05:10 -0700 (Mon, 13 Aug 2007)
Log Message:
-----------
Squash final nesting bug
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/N3Serializer.php
trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
Modified: trunk/rdfapi-php/api/syntax/N3Serializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 17:51:59 UTC (rev 520)
+++ trunk/rdfapi-php/api/syntax/N3Serializer.php 2007-08-13 18:05:10 UTC (rev 521)
@@ -181,20 +181,29 @@
arsort($count);
- foreach ( $count as $k=>$v) {
+ foreach ( $count as $k => $v) {
$this->doResource($resources[$k]);
// $this->res.=" .\n";
}
- $c = 0;
- foreach ($this->resourcetext as $r => $t) {
- if (preg_match_all('/'.MAGIC_STRING.'([^ ]+)'.MAGIC_STRING.'/', $t, $ms, PREG_SET_ORDER)) {
- foreach ($ms as $mseach) {
- $rp = $this->resourcetext[$mseach[1]];
- $t = preg_replace('/'.MAGIC_STRING.$mseach[1].MAGIC_STRING.'/', $rp, $t);
+ //make all replacements
+ do {
+ $bReplacements = false;
+ foreach ($this->resourcetext as $r => $t) {
+ if (preg_match_all('/'.MAGIC_STRING.'([^ ]+)'.MAGIC_STRING.'/', $t, $ms, PREG_SET_ORDER)) {
+ foreach ($ms as $mseach) {
+ $rp = $this->resourcetext[$mseach[1]];
+ $this->resourcetext[$r] = preg_replace('/'.MAGIC_STRING.$mseach[1].MAGIC_STRING.'/', $rp, $t);
+ $bReplacements = true;
+ }
}
+
}
+ } while ($bReplacements);
+ //after all replacements took place, put the lines out
+ $c = 0;
+ foreach ($this->resourcetext as $r => $t) {
if ($this->debug) {
$this->res .= $c . ': ';
}
Modified: trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 17:51:59 UTC (rev 520)
+++ trunk/rdfapi-php/test/unit/Syntax/n3Serializer_test.php 2007-08-13 18:05:10 UTC (rev 521)
@@ -338,8 +338,8 @@
- function testNest()
- {return;
+ function testNestDeeply()
+ {
$mod = new MemModel();
$b100 = new BlankNode($mod);
$b110 = new BlankNode($mod);
@@ -374,11 +374,9 @@
//test if it can be loaded
$par = new N3Parser();
$mod2 = $par->parse2model($str, false);
- var_dump($str);//, $mod2->triples);
+ //var_dump($str, $mod2->triples);
- $this->assertEqual($mod->size(), $mod2->size(), 'Original model size and loaded model size should equal');
- $this->assertTrue($mod->containsAll($mod2), 'Original model should contain all triples of loaded model');
- $this->assertTrue($mod2->containsAll($mod), 'Loaded model should contain all triples of original model');
+ $this->compareModelsIgnoringBlankNodes($mod, $mod2);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-14 09:22:38
|
Revision: 522
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=522&view=rev
Author: cweiske
Date: 2007-08-14 02:22:22 -0700 (Tue, 14 Aug 2007)
Log Message:
-----------
PHP file were not closed
Modified Paths:
--------------
trunk/rdfapi-php/api/resModel/ResIterator.php
trunk/rdfapi-php/api/resModel/ResModel.php
trunk/rdfapi-php/test/unit/Model/ModelFactory_tests.php
trunk/rdfapi-php/test/unit/Model/Model_tests.php
Modified: trunk/rdfapi-php/api/resModel/ResIterator.php
===================================================================
--- trunk/rdfapi-php/api/resModel/ResIterator.php 2007-08-13 18:05:10 UTC (rev 521)
+++ trunk/rdfapi-php/api/resModel/ResIterator.php 2007-08-14 09:22:22 UTC (rev 522)
@@ -279,6 +279,7 @@
break;
case 'OntProperty':
+
return $this->associatedModel->createOntProperty($resource->getLabel());
break;
@@ -292,4 +293,6 @@
}
return $resource;
}
-}
\ No newline at end of file
+}
+
+?>
\ No newline at end of file
Modified: trunk/rdfapi-php/api/resModel/ResModel.php
===================================================================
--- trunk/rdfapi-php/api/resModel/ResModel.php 2007-08-13 18:05:10 UTC (rev 521)
+++ trunk/rdfapi-php/api/resModel/ResModel.php 2007-08-14 09:22:22 UTC (rev 522)
@@ -870,4 +870,6 @@
-}
\ No newline at end of file
+}
+
+?>
\ No newline at end of file
Modified: trunk/rdfapi-php/test/unit/Model/ModelFactory_tests.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/ModelFactory_tests.php 2007-08-13 18:05:10 UTC (rev 521)
+++ trunk/rdfapi-php/test/unit/Model/ModelFactory_tests.php 2007-08-14 09:22:22 UTC (rev 522)
@@ -160,3 +160,5 @@
new Literal('Fred')));
}
}
+
+?>
\ No newline at end of file
Modified: trunk/rdfapi-php/test/unit/Model/Model_tests.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/Model_tests.php 2007-08-13 18:05:10 UTC (rev 521)
+++ trunk/rdfapi-php/test/unit/Model/Model_tests.php 2007-08-14 09:22:22 UTC (rev 522)
@@ -50,3 +50,5 @@
$this->assertIdentical(1, $ont->size());
}
}
+
+?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-16 09:06:08
|
Revision: 529
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=529&view=rev
Author: cweiske
Date: 2007-08-16 02:06:06 -0700 (Thu, 16 Aug 2007)
Log Message:
-----------
getParsedNamespaces() should return empty array instead of
boolean false if there are no namespaces
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbModel.php
trunk/rdfapi-php/test/unit/Model/dBModel_test.php
Modified: trunk/rdfapi-php/api/model/DbModel.php
===================================================================
--- trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 08:57:35 UTC (rev 528)
+++ trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:06:06 UTC (rev 529)
@@ -1156,7 +1156,7 @@
function getParsedNamespaces(){
$sql = "SELECT * FROM namespaces
WHERE modelID = " .$this->modelID;
- $temp=false;
+ $temp=array();
$res = $this->dbConn->execute($sql);
if($res){
while (!$res->EOF) {
Modified: trunk/rdfapi-php/test/unit/Model/dBModel_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 08:57:35 UTC (rev 528)
+++ trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:06:06 UTC (rev 529)
@@ -13,14 +13,16 @@
* @access public
*/
-class dBModel_test extends UnitTestCase {
+class dBModel_test extends UnitTestCase
+{
+ protected static $strModelUri = 'http://example.org/rap-unittests-dbmodel';
function testSize(){
$mysql_database = $this->createDatabaseConnection();
//$mysql_database->createTables('MySQL');
$_SESSION['test']='DbModel size test';
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(), self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$this->assertEqual($dbmodel->size(),1);
$dbmodel->delete();
}
@@ -29,8 +31,8 @@
function testAdd(){
$_SESSION['test']='DbModel add test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$statement=new Statement(new Resource('http://www.example.org/subject2'),new Resource('http://www.example.org/predicate2'),new Resource('http://www.example.org/object2'));
$dbmodel->add($statement);
$this->assertTrue($dbmodel->contains($statement));
@@ -42,8 +44,8 @@
function testRemove(){
$_SESSION['test']='DbModel remove test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$statement=new Statement(new Resource('http://www.example.org/subject2'),new Resource('http://www.example.org/predicate2'),new Resource('http://www.example.org/object2'));
$dbmodel->remove($statement);
$mod1=$dbmodel->getMemModel();
@@ -55,8 +57,8 @@
function testSetBaseUri(){
$_SESSION['test']='DbModel setBaseURI test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$this->assertEqual($dbmodel->baseURI,'http://www.example.org#');
$dbmodel->delete();
}
@@ -65,8 +67,8 @@
function testContains(){
$_SESSION['test']='DbModel testContains test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$stat=new Statement(new Resource('http://www.example.org/subject1'),new Resource('http://www.example.org/predicate1'),new Resource('http://www.example.org/object1'));
$stat2=new Statement(new Resource('http://www.example.org/subject2'),new Resource('http://www.example.org/predicate2'),new Resource('http://www.example.org/object2'));
$this->assertTrue($dbmodel->contains($stat));
@@ -77,8 +79,8 @@
function testContainsAll(){
$_SESSION['test']='DbModel testContainsAll test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$memModel=$this->_generateModel();
$this->assertTrue($dbmodel->containsAll($memModel));
$dbmodel->delete();
@@ -87,8 +89,8 @@
function testContainsAny(){
$_SESSION['test']='DbModel testContainsAny test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModel(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModel(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$memModel=$this->_generateModel();
$this->assertTrue($dbmodel->containsAny($memModel));
$dbmodel->delete();
@@ -98,8 +100,8 @@
function testLiteral(){
$_SESSION['test']='DbModel testContainsAny test';
$mysql_database = $this->createDatabaseConnection();
- $mysql_database->putModel($this->_generateModelLiteral(),'http://www.example.org');
- $dbmodel=$mysql_database->getModel('http://www.example.org');
+ $mysql_database->putModel($this->_generateModelLiteral(),self::$strModelUri);
+ $dbmodel=$mysql_database->getModel(self::$strModelUri);
$memModel=$dbmodel->getMemModel();
$stat=$memModel->triples[0];
$obj=$stat->getObject();
@@ -108,8 +110,19 @@
$dbmodel->delete();
}
+ function testNamespaces()
+ {
+ $_SESSION['test']='DbModel testNamespaces test';
+ $mysql_database = $this->createDatabaseConnection();
+ $mysql_database->putModel($this->_generateModelLiteral(),self::$strModelUri);
+ $dbmodel = $mysql_database->getModel(self::$strModelUri);
+ //no namespaces
+ $this->assertIdentical(array(), $dbmodel->getParsedNamespaces());
+ }
+
+
//===================================================================
// helper functions
//===================================================================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-16 09:12:29
|
Revision: 530
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=530&view=rev
Author: cweiske
Date: 2007-08-16 02:12:27 -0700 (Thu, 16 Aug 2007)
Log Message:
-----------
When deleting model, also delete namespaces
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbModel.php
trunk/rdfapi-php/test/unit/Model/dBModel_test.php
Modified: trunk/rdfapi-php/api/model/DbModel.php
===================================================================
--- trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:06:06 UTC (rev 529)
+++ trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:12:27 UTC (rev 530)
@@ -940,6 +940,8 @@
WHERE modelID=' .$this->modelID);
$this->dbConn->execute('DELETE FROM statements
WHERE modelID=' .$this->modelID);
+ $this->dbConn->execute('DELETE FROM namespaces
+ WHERE modelID=' .$this->modelID);
if (!$this->dbConn->completeTrans())
echo $this->dbConn->errorMsg();
Modified: trunk/rdfapi-php/test/unit/Model/dBModel_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:06:06 UTC (rev 529)
+++ trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:12:27 UTC (rev 530)
@@ -118,8 +118,17 @@
$dbmodel = $mysql_database->getModel(self::$strModelUri);
//no namespaces
+var_dump($dbmodel->getParsedNamespaces());
$this->assertIdentical(array(), $dbmodel->getParsedNamespaces());
+ //one namespace
+ $dbmodel->addNamespace('test', 'http://test.org');
+ $this->assertEqual(
+ array('http://test.org' => 'test'),
+ $dbmodel->getParsedNamespaces()
+ );
+
+ $dbmodel->delete();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-16 09:19:18
|
Revision: 531
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=531&view=rev
Author: cweiske
Date: 2007-08-16 02:19:14 -0700 (Thu, 16 Aug 2007)
Log Message:
-----------
Finishing namespace unit test
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbModel.php
trunk/rdfapi-php/test/unit/Model/dBModel_test.php
Modified: trunk/rdfapi-php/api/model/DbModel.php
===================================================================
--- trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:12:27 UTC (rev 530)
+++ trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:19:14 UTC (rev 531)
@@ -1267,7 +1267,7 @@
$rs =& $this->dbConn->execute($sql);
if (!$rs)
- $this->dbConn->errorMsg();
+ return $this->dbConn->errorMsg();
}
Modified: trunk/rdfapi-php/test/unit/Model/dBModel_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:12:27 UTC (rev 530)
+++ trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:19:14 UTC (rev 531)
@@ -117,8 +117,8 @@
$mysql_database->putModel($this->_generateModelLiteral(),self::$strModelUri);
$dbmodel = $mysql_database->getModel(self::$strModelUri);
+
//no namespaces
-var_dump($dbmodel->getParsedNamespaces());
$this->assertIdentical(array(), $dbmodel->getParsedNamespaces());
//one namespace
@@ -128,6 +128,56 @@
$dbmodel->getParsedNamespaces()
);
+ //two namespaces
+ $dbmodel->addNamespace('test2', 'http://test2.org');
+ $this->assertEqual(
+ array(
+ 'http://test.org' => 'test',
+ 'http://test2.org' => 'test2',
+ ),
+ $dbmodel->getParsedNamespaces()
+ );
+
+ //adding multiple namespaces
+ $dbmodel->addParsedNamespaces(
+ array(
+ 'http://test3.org' => 'test3',
+ 'http://test4.org' => 'test4',
+ )
+ );
+ $this->assertEqual(
+ array(
+ 'http://test.org' => 'test',
+ 'http://test2.org' => 'test2',
+ 'http://test3.org' => 'test3',
+ 'http://test4.org' => 'test4',
+ ),
+ $dbmodel->getParsedNamespaces()
+ );
+
+ //adding empty array
+ $dbmodel->addParsedNamespaces(array());
+ $this->assertEqual(
+ array(
+ 'http://test.org' => 'test',
+ 'http://test2.org' => 'test2',
+ 'http://test3.org' => 'test3',
+ 'http://test4.org' => 'test4',
+ ),
+ $dbmodel->getParsedNamespaces()
+ );
+
+ //removing namespace
+ $dbmodel->removeNamespace('http://test2.org');
+ $this->assertEqual(
+ array(
+ 'http://test.org' => 'test',
+ 'http://test3.org' => 'test3',
+ 'http://test4.org' => 'test4',
+ ),
+ $dbmodel->getParsedNamespaces()
+ );
+
$dbmodel->delete();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-08-16 09:32:05
|
Revision: 533
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=533&view=rev
Author: cweiske
Date: 2007-08-16 02:32:03 -0700 (Thu, 16 Aug 2007)
Log Message:
-----------
If getParsedNamespaces() does not return false if there are no namespaces,
we break a mass of tests
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbModel.php
trunk/rdfapi-php/test/unit/Model/dBModel_test.php
Modified: trunk/rdfapi-php/api/model/DbModel.php
===================================================================
--- trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:19:56 UTC (rev 532)
+++ trunk/rdfapi-php/api/model/DbModel.php 2007-08-16 09:32:03 UTC (rev 533)
@@ -1151,15 +1151,18 @@
/**
* Returns the models namespaces.
*
- * @author Tobias Gau�<tob...@we...>
+ * @author Tobias Gauss <tob...@we...>
+ * @return mixed Array of key-value pairs. Namespace is the key,
+ * prefix the value. If no namespaces are found,
+ * boolean false is returned.
+ *
* @access public
- * @return Array
*/
function getParsedNamespaces(){
$sql = "SELECT * FROM namespaces
WHERE modelID = " .$this->modelID;
- $temp=array();
- $res = $this->dbConn->execute($sql);
+ $temp = false;
+ $res = $this->dbConn->execute($sql);
if($res){
while (!$res->EOF) {
$temp[$res->fields[1]]=$res->fields[2];
@@ -1176,9 +1179,10 @@
* the parser. !!!! addParsedNamespaces() not overwrites manual
* added namespaces in the model !!!!
*
- * @author Tobias Gau�<tob...@we...>
+ * @author Tobias Gauss <tob...@we...>
+ * @param array $newNs Array of namespace => prefix assignments
+ *
* @access public
- * @param Array $newNs
*/
function addParsedNamespaces($newNs){
if($newNs)
@@ -1191,9 +1195,11 @@
/**
* Adds a namespace and prefix to the model.
*
- * @author Tobias Gau�<tob...@we...>
+ * @author Tobias Gauss <tob...@we...>
+ * @param string $prefix Prefix
+ * @param string $nmsp Namespace URI
+ *
* @access public
- * @param String $prefix, String $nmsp
*/
function addNamespace($prefix,$nmsp){
@@ -1254,20 +1260,26 @@
}
/**
- * removes a single namespace from the model
+ * Removes a single namespace from the model
*
- * @author Tobias Gau�<tob...@we...>
+ * @author Tobias Gauss <tob...@we...>
+ * @param string $nmsp Namespace URI
+ *
+ * @return mixed True if all went well, error message otherwise
+ *
* @access public
- * @param String $nmsp
*/
function removeNamespace($nmsp){
- $sql = 'DELETE FROM namespaces
+ $sql = 'DELETE FROM namespaces
WHERE modelID=' .$this->modelID." AND namespace=". $this->dbConn->qstr($nmsp);
- $rs =& $this->dbConn->execute($sql);
- if (!$rs)
- return $this->dbConn->errorMsg();
+ $rs =& $this->dbConn->execute($sql);
+ if (!$rs)
+ return $this->dbConn->errorMsg();
+ else {
+ return true;
+ }
}
Modified: trunk/rdfapi-php/test/unit/Model/dBModel_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:19:56 UTC (rev 532)
+++ trunk/rdfapi-php/test/unit/Model/dBModel_test.php 2007-08-16 09:32:03 UTC (rev 533)
@@ -119,7 +119,7 @@
$dbmodel = $mysql_database->getModel(self::$strModelUri);
//no namespaces
- $this->assertIdentical(array(), $dbmodel->getParsedNamespaces());
+ $this->assertIdentical(false, $dbmodel->getParsedNamespaces());
//one namespace
$dbmodel->addNamespace('test', 'http://test.org');
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-09-18 17:55:19
|
Revision: 537
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=537&view=rev
Author: cweiske
Date: 2007-09-18 10:55:11 -0700 (Tue, 18 Sep 2007)
Log Message:
-----------
Allow SPARQL debugging
Modified Paths:
--------------
trunk/rdfapi-php/api/sparql/Query.php
trunk/rdfapi-php/api/sparql/SparqlEngineDb.php
trunk/rdfapi-php/api/sparql/SparqlParser.php
trunk/rdfapi-php/test/config.php.dist
trunk/rdfapi-php/test/sparql-test.php
trunk/rdfapi-php/test/sparqlDb-test.php
Modified: trunk/rdfapi-php/api/sparql/Query.php
===================================================================
--- trunk/rdfapi-php/api/sparql/Query.php 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/api/sparql/Query.php 2007-09-18 17:55:11 UTC (rev 537)
@@ -20,6 +20,12 @@
protected $base;
/**
+ * Original SPARQL query string
+ * @var string
+ */
+ protected $queryString = null;
+
+ /**
* Array that contains used prefixes and namespaces.
* Key is the prefix, value the namespace.
*
@@ -555,6 +561,30 @@
return true;
}//public function isIncomplete()
+
+
+ /**
+ * Sets the orignal query string
+ *
+ * @param string $queryString SPARQL query string
+ */
+ public function setQueryString($queryString)
+ {
+ $this->queryString = $queryString;
+ }//public function setQueryString($queryString)
+
+
+
+ /**
+ * Returns the orignal query string
+ *
+ * @return string SPARQL query string
+ */
+ public function getQueryString()
+ {
+ return $this->queryString;
+ }//public function getQueryString()
+
}// end class: Query.php
@@ -648,6 +678,7 @@
{
return $this->getName();
}
+
}//class Query_ResultVariable
?>
\ No newline at end of file
Modified: trunk/rdfapi-php/api/sparql/SparqlEngineDb.php
===================================================================
--- trunk/rdfapi-php/api/sparql/SparqlEngineDb.php 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/api/sparql/SparqlEngineDb.php 2007-09-18 17:55:11 UTC (rev 537)
@@ -115,16 +115,23 @@
*/
public function queryModel($dataset, Query $query, $resultform = false)
{
+ if (isset($GLOBALS['debugSparql']) && $GLOBALS['debugSparql']) {
+ echo "\n" . 'SPARQL query: ' . $query->getQueryString() . "\n";
+ }
+
$this->query = $query;
$this->dataset = $dataset;
+
$qsimp = new SparqlEngineDb_QuerySimplifier();
$qsimp->simplify($this->query);
+
$this->sg = new SparqlEngineDb_SqlGenerator ($this->query, $this->dbConn, $this->arModelIds);
$this->rc = new SparqlEngineDb_ResultConverter($this->query, $this->sg, $this);
$this->ts = new SparqlEngineDb_TypeSorter ($this->query, $this->dbConn);
+
$this->setOptions();
- if($this->query->isEmpty()){
+ if ($this->query->isEmpty()){
$vartable[0]['patternResult'] = null;
return $this->returnResult($vartable, $resultform);
}
@@ -312,7 +319,10 @@
// I want associative arrays.
$oldmode = $this->dbConn->SetFetchMode(ADODB_FETCH_ASSOC);
-//var_dump($strSql);
+ if (isset($GLOBALS['debugSparql']) && $GLOBALS['debugSparql']) {
+ echo 'SQL query: ' . $strSql . "\n";
+ }
+
if ($nLimit === null && $nOffset == 0) {
$ret = $this->dbConn->execute($strSql);
} else if ($nLimit === null) {
Modified: trunk/rdfapi-php/api/sparql/SparqlParser.php
===================================================================
--- trunk/rdfapi-php/api/sparql/SparqlParser.php 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/api/sparql/SparqlParser.php 2007-09-18 17:55:11 UTC (rev 537)
@@ -105,9 +105,10 @@
$this->prepare();
if ($queryString) {
+ $this->query->setQueryString($queryString);
$uncommentedQuery = $this->uncomment($queryString);
$this->tokenize($uncommentedQuery);
- $this->querystring = $uncommentedQuery;
+ $this->queryString = $uncommentedQuery;
$this->parseQuery();
if (!$this->query->isComplete()) {
throw new SparqlParserException(
@@ -136,7 +137,7 @@
protected function prepare()
{
$this->query = new Query();
- $this->querystring = null;
+ $this->queryString = null;
$this->tokens = array();
$this->tmp = null;
// add the default prefixes defined in constants.php
@@ -147,7 +148,7 @@
/**
- * Tokenizes the querystring.
+ * Tokenizes the query string.
*
* @param String $queryString
* @return void
@@ -1481,6 +1482,7 @@
* Parses an RDF collection.
*
* @param TriplePattern $trp
+ *
* @return Node The first parsed label
*/
protected function parseCollection(&$trp)
@@ -1498,7 +1500,7 @@
}
$trp[] = new QueryTriple($this->parseNode($tmpLabel),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"));
return $firstLabel;
- }
+ }//protected function parseCollection(&$trp)
}// end class: SparqlParser.php
Modified: trunk/rdfapi-php/test/config.php.dist
===================================================================
--- trunk/rdfapi-php/test/config.php.dist 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/test/config.php.dist 2007-09-18 17:55:11 UTC (rev 537)
@@ -21,6 +21,9 @@
//enable this to get more information about failing unit tests
//$GLOBALS['debugTests'] = true;
+//debug SPARQL engine
+//$GLOBALS['debugSparql'] = true;
+
//used in W3C earl report serialization
$GLOBALS['earlReport'] = array(
'reporter' => array(
Modified: trunk/rdfapi-php/test/sparql-test.php
===================================================================
--- trunk/rdfapi-php/test/sparql-test.php 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/test/sparql-test.php 2007-09-18 17:55:11 UTC (rev 537)
@@ -9,9 +9,9 @@
$model->load(SPARQL_TESTFILES . 'data/model9.n3');
$qs = 'SELECT * WHERE { ?s ?p ?o}';
-$result = $model->sparqlQuery($qs, 'HTML');
+$result = $model->sparqlQuery($qs);
-header('Content-Type: text/html');
-echo $result . "\n";
-//var_dump($result);
+//header('Content-Type: text/html');
+//echo $result . "\n";
+var_dump($result);
?>
\ No newline at end of file
Modified: trunk/rdfapi-php/test/sparqlDb-test.php
===================================================================
--- trunk/rdfapi-php/test/sparqlDb-test.php 2007-08-20 17:21:35 UTC (rev 536)
+++ trunk/rdfapi-php/test/sparqlDb-test.php 2007-09-18 17:55:11 UTC (rev 537)
@@ -36,6 +36,10 @@
UNION {?value ?p ?o . FILTER (isIRI(?value)) }
}
EOT;
-var_dump($dbModel->sparqlQuery($qs));
+$qs = <<<EOT
+SELECT DISTINCT datatype(?o) as ?dt WHERE { ?s ?p ?o} LIMIT 3
+EOT;
+$qs= '-';
+var_dump($database->sparqlQuery($qs, null));
//echo $dbModel->sparqlQuery($qs, 'HTML');
?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-09-19 19:35:24
|
Revision: 538
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=538&view=rev
Author: cweiske
Date: 2007-09-19 12:35:23 -0700 (Wed, 19 Sep 2007)
Log Message:
-----------
- Make tokenization function testable
- Add support for """ quotations
Modified Paths:
--------------
trunk/rdfapi-php/api/sparql/SparqlParser.php
trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php
Modified: trunk/rdfapi-php/api/sparql/SparqlParser.php
===================================================================
--- trunk/rdfapi-php/api/sparql/SparqlParser.php 2007-09-18 17:55:11 UTC (rev 537)
+++ trunk/rdfapi-php/api/sparql/SparqlParser.php 2007-09-19 19:35:23 UTC (rev 538)
@@ -106,9 +106,9 @@
if ($queryString) {
$this->query->setQueryString($queryString);
- $uncommentedQuery = $this->uncomment($queryString);
- $this->tokenize($uncommentedQuery);
+ $uncommentedQuery = $this->uncomment($queryString);
$this->queryString = $uncommentedQuery;
+ $this->tokens = self::tokenize($uncommentedQuery);
$this->parseQuery();
if (!$this->query->isComplete()) {
throw new SparqlParserException(
@@ -126,7 +126,7 @@
$this->query->isEmpty = true;
}
return $this->query;
- }
+ }//public function parse($queryString = false)
@@ -143,35 +143,66 @@
// add the default prefixes defined in constants.php
global $default_prefixes;
$this->query->prefixes = $default_prefixes;
- }
+ }//protected function prepare()
/**
- * Tokenizes the query string.
+ * Tokenizes the query string into $tokens.
+ * The query may not contain any comments.
*
- * @param String $queryString
- * @return void
+ * @param string $queryString Query to split into tokens
+ *
+ * @return array Tokens
*/
- protected function tokenize($queryString)
+ public static function tokenize($queryString)
{
- $queryString = trim($queryString);
- $specialChars = array(" ", "\t", "\r", "\n", ",", "(", ")","{","}",'"',"'",";","[","]");
- $len = strlen($queryString);
- $this->tokens[0]='';
- $n = 0;
- for ($i=0; $i<$len; ++$i) {
+ $queryString = trim($queryString);
+ $specialChars = array(' ', "\t", "\r", "\n", ',', '\\', '(', ')','{','}','"',"'",';','[',']');
+ $len = strlen($queryString);
+ $tokens = array('');
+ $n = 0;
+
+ for ($i = 0; $i < $len; ++$i) {
if (!in_array($queryString{$i}, $specialChars)) {
- $this->tokens[$n] .= $queryString{$i};
+ $tokens[$n] .= $queryString{$i};
} else {
- if ($this->tokens[$n] != '') {
+ if ($tokens[$n] != '') {
++$n;
+ if (!isset($tokens[$n])) {
+ $tokens[$n] = '';
+ }
}
- $this->tokens[$n] = $queryString{$i};
- $this->tokens[++$n] = '';
+ if ($queryString{$i} == "'" && $n > 1
+ && $tokens[$n - 2] == "'" && $tokens[$n - 1] == "'"
+ ) {
+ //special ''' quotation
+ $tokens[$n - 2] = "'''";
+ $tokens[$n - 1] = '';
+ unset($tokens[$n]);
+ --$n;
+ continue;
+ } else if ($queryString{$i} == '"' && $n > 1
+ && $tokens[$n - 2] == '"' && $tokens[$n - 1] == '"'
+ ) {
+ //special """ quotation
+ $tokens[$n - 2] = '"""';
+ $tokens[$n - 1] = '';
+ unset($tokens[$n]);
+ --$n;
+ continue;
+ } else if ($queryString{$i} == '\\') {
+ $tokens[$n] .= substr($queryString, $i, 2);
+ ++$i;
+ continue;
+ }
+ $tokens[$n] = $queryString{$i};
+ $tokens[++$n] = '';
}
}
- }
+//var_dump($tokens);
+ return $tokens;
+ }//public static function tokenize($queryString)
@@ -184,14 +215,12 @@
*/
protected function uncomment($queryString)
{
- // php appears to escape quotes, so unescape them
- $queryString = str_replace('\"',"'",$queryString);
- $queryString = str_replace("\'",'"',$queryString);
-
$regex ="/((\"[^\"]*\")|(\'[^\']*\')|(\<[^\>]*\>))|(#.*)/";
return preg_replace($regex,'\1',$queryString);
- }
+ }//protected function uncomment($queryString)
+
+
/**
* Starts parsing the tokenized SPARQL Query.
*
@@ -237,7 +266,7 @@
}
} while (next($this->tokens));
- }
+ }//protected function parseQuery()
@@ -545,45 +574,56 @@
}
+
/**
* Checks if $token is a Literal.
*
- * @param String $token The token
+ * @param string $token The token
+ *
* @return boolean TRUE if the token is a Literal false if not
*/
- protected function literalCheck($token){
- $pattern="/^[\"\'].*$/";
- if(preg_match($pattern,$token)>0)
- return true;
+ protected function literalCheck($token)
+ {
+ $pattern = "/^[\"\'].*$/";
+ if (preg_match($pattern,$token) > 0) {
+ return true;
+ }
return false;
- }
+ }//protected function literalCheck($token)
+
+
/**
* FastForward until next token which is not blank.
*
* @return void
*/
- protected function _fastForward(){
+ protected function _fastForward()
+ {
next($this->tokens);
while(current($this->tokens)==" "|current($this->tokens)==chr(10)|current($this->tokens)==chr(13)|current($this->tokens)==chr(9)){
next($this->tokens);
}
- return;
- }
+ }//protected function _fastForward()
+
+
/**
* Rewind until next token which is not blank.
*
* @return void
*/
- protected function _rewind(){
+ protected function _rewind()
+ {
prev($this->tokens);
while(current($this->tokens)==" "|current($this->tokens)==chr(10)|current($this->tokens)==chr(13)|current($this->tokens)==chr(9)){
prev($this->tokens);
}
return;
- }
+ }//protected function _rewind()
+
+
/**
* Parses a graph pattern.
*
@@ -1299,12 +1339,13 @@
* Parses a String to an RDF node.
*
* @param String $node
+ *
* @return Node The parsed RDF node
* @throws SparqlParserException
*/
protected function parseNode($node = false)
{
- $eon = false;
+ //$eon = false;
if ($node) {
$node = $node;
} else {
@@ -1343,19 +1384,12 @@
$node = new Resource($node);
return $node;
} else if ($this->literalCheck($node)) {
- do {
- switch(substr($node,0,1)){
- case '"':
- $this->parseLiteral($node,'"');
- $eon = true;
- break;
- case "'":
- $this->parseLiteral($node,"'");
- $eon = true;
- break;
- }
- } while(!$eon);
-
+ $ch = substr($node, 0, 1);
+ $chLong = str_repeat($ch, 3);
+ if (substr($node, 0, 3) == $chLong) {
+ $ch = $chLong;
+ }
+ $this->parseLiteral($node, $ch);
} else if ($this->varCheck($node)) {
$pos = strpos($node,'.');
if ($pos) {
@@ -1381,21 +1415,24 @@
return $this->parseNode($node);
} else {
throw new SparqlParserException(
- $node . " is neither a valid rdf- node nor a variable.",
+ '"' . $node . '" is neither a valid rdf- node nor a variable.',
null,
key($this->tokens)
);
}
return $node;
- }
+ }//protected function parseNode($node = false)
+
+
/**
* Checks if there is a datatype given and appends it to the node.
*
- * @param String $node
+ * @param string $node Node to check
+ *
* @return void
*/
- protected function checkDtypeLang(&$node)
+ protected function checkDtypeLang(&$node, $nSubstrLength = 1)
{
$this->_fastForward();
switch (substr(current($this->tokens), 0, 1)) {
@@ -1411,24 +1448,26 @@
break;
case '@':
$node = new Literal(
- substr($node, 1, -1),
- substr(current($this->tokens), 1)
+ substr($node, $nSubstrLength, -$nSubstrLength),
+ substr(current($this->tokens), $nSubstrLength)
);
break;
default:
prev($this->tokens);
- $node = new Literal(substr($node, 1, -1));
+ $node = new Literal(substr($node, $nSubstrLength, -$nSubstrLength));
break;
}
+ }//protected function checkDtypeLang(&$node, $nSubstrLength = 1)
- }
+
/**
* Parses a literal.
*
* @param String $node
* @param String $sep used separator " or '
+ *
* @return void
*/
protected function parseLiteral(&$node, $sep)
@@ -1437,13 +1476,16 @@
next($this->tokens);
$node = $node.current($this->tokens);
} while (current($this->tokens) != $sep);
- $this->checkDtypeLang($node);
- }
+ $this->checkDtypeLang($node, strlen($sep));
+ }//protected function parseLiteral(&$node, $sep)
+
+
/**
* Checks if the Node is a typed Literal.
*
* @param String $node
+ *
* @return boolean TRUE if typed FALSE if not
*/
protected function dtypeCheck(&$node)
@@ -1476,8 +1518,10 @@
return true;
}
return false;
- }
+ }//protected function dtypeCheck(&$node)
+
+
/**
* Parses an RDF collection.
*
Modified: trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php 2007-09-18 17:55:11 UTC (rev 537)
+++ trunk/rdfapi-php/test/unit/Sparql/SparqlParserTests_test.php 2007-09-19 19:35:23 UTC (rev 538)
@@ -67,6 +67,16 @@
+ function testTokenizer()
+ {
+ $this->assertEqual(
+ array('abc', "'", 'hi', "'", "'", 'def', "'''", 'rst', "\'", "'", "'", 'xyz'),
+ SparqlParser::tokenize("abc'hi''def'''rst\\'''xyz")
+ );
+ }//function testTokenizer()
+
+
+
function testEdgeCases()
{
$query = <<<EOT
@@ -147,6 +157,7 @@
$parser = new SparqlParser();
foreach ($_SESSION['sparql_dawg2_tests'] as $test) {
+echo $test['title'] . "\n";
//use syntax tests only
if (!isset($test['type']) ||
($test['type'] != 'syntax-positive' &&
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-10-09 15:48:07
|
Revision: 541
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=541&view=rev
Author: cweiske
Date: 2007-10-09 08:48:01 -0700 (Tue, 09 Oct 2007)
Log Message:
-----------
Setup script for CLI
Make DbStore have a cleaner API
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbStore.php
Added Paths:
-----------
trunk/rdfapi-php/test/setup.php
Modified: trunk/rdfapi-php/api/model/DbStore.php
===================================================================
--- trunk/rdfapi-php/api/model/DbStore.php 2007-09-20 07:35:41 UTC (rev 540)
+++ trunk/rdfapi-php/api/model/DbStore.php 2007-10-09 15:48:01 UTC (rev 541)
@@ -26,17 +26,35 @@
*/
-class DbStore extends Object{
+class DbStore extends Object
+{
+ /**
+ * Array with all supported database types
+ *
+ * @var array
+ */
+ public static $arSupportedDbTypes = array(
+ "MySQL",
+ "MSSQL",
+ 'MsAccess'
+ );
-/**
- * Database connection object
- *
- * @var object ADOConnection
- * @access private
- */
- var $dbConn;
+ /**
+ * Database connection object
+ *
+ * @var object ADOConnection
+ * @access private
+ */
+ var $dbConn;
/**
+ * Database driver name
+ *
+ * @var string
+ */
+ protected $driver = null;
+
+ /**
* SparqlParser so we can re-use it
* @var Parser
*/
@@ -62,6 +80,7 @@
// create a new connection object
$this->dbConn =& ADONewConnection($dbDriver);
+ $this->driver = $dbDriver;
//activate the ADOdb DEBUG mode
if (ADODB_DEBUG_MODE == '1')
@@ -79,33 +98,7 @@
}
-/**
- * Create tables and indexes for the given database type.
- * Currently supported: MsAccess and MySQL.
- * If you want to use other databases, you will have to create tables by yourself
- * according to the abstract <a href="database_schema.html">database schema</a>
- * described in the API documentation.
- *
- * @param string $databaseType
- * @throws PhpError
- * @access public
- */
- function createTables($databaseType) {
- if (!strcasecmp($databaseType, 'MsAccess'))
- $this->_createTables_MsAccess();
- elseif (!strcasecmp($databaseType, 'MySQL'))
- $this->_createTables_MySql();
- elseif (!strcasecmp($databaseType, 'MSSQL'))
- $this->_createTables_mssql();
- else {
- $errmsg = RDFAPI_ERROR . "(class: DbStore; method: createTables('$databaseType')):
- Currently only MsAcces, MySQL and MSSQL supported.";
- trigger_error($errmsg, E_USER_ERROR);
- }
- }
-
-
/**
* List all DbModels stored in the database.
*
@@ -303,206 +296,282 @@
}
-/**
- * Create tables and indexes for MsAccess database
- *
- * @throws SqlError
- * @access private
- */
- function _createTables_MsAccess() {
- $this->dbConn->startTrans();
+ /**
+ * Sets up tables for RAP.
+ * DOES NOT CHECK IF TABLES ALREADY EXIST
+ *
+ * @param string $databaseType Database driver name (e.g. MySQL)
+ *
+ * @throws Exception If database type is unsupported
+ * @access public
+ **/
+ public function createTables($databaseType = null)
+ {
+ $driver = $this->getDriver($databaseType);
+ $this->assertDriverSupported($driver);
- $this->dbConn->execute('CREATE TABLE models
- (modelID long primary key,
- modelURI varchar not null,
- baseURI varchar)');
+ $createFunc = '_createTables_' . $driver;
+ return $this->$createFunc();
+ }//public function createTables($databaseType="MySQL")
- $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
- $this->dbConn->execute('CREATE TABLE statements
- (modelID long,
- subject varchar,
- predicate varchar,
- object Memo,
- l_language varchar,
- l_datatype varchar,
- subject_is varchar(1),
- object_is varchar(1),
- primary key (modelID, subject, predicate, object,
- l_language, l_datatype))');
- $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
- $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject)');
- $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate)');
- $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object)');
+ /**
+ * Create tables and indexes for MsAccess database
+ *
+ * @return boolean true If all is ok
+ *
+ * @throws Exception
+ */
+ protected function _createTables_MsAccess()
+ {
+ $this->dbConn->startTrans();
- $this->dbConn->execute('CREATE TABLE namespaces
- (modelID long,
- namespace varchar,
- prefix varchar,
- primary key (modelID, namespace, prefix))');
+ $this->dbConn->execute('CREATE TABLE models
+ (modelID long primary key,
+ modelURI varchar not null,
+ baseURI varchar)');
- $this->dbConn->execute('CREATE INDEX n_name_idx ON namespaces (namespace)');
- $this->dbConn->execute('CREATE INDEX n_pref_idx ON namespaces (prefix)');
+ $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
- $this->dbConn->execute("CREATE TABLE datasets
- (datasetName varchar,
- defaultModelUri varchar,
- primary key (datasetName))");
+ $this->dbConn->execute('CREATE TABLE statements
+ (modelID long,
+ subject varchar,
+ predicate varchar,
+ object Memo,
+ l_language varchar,
+ l_datatype varchar,
+ subject_is varchar(1),
+ object_is varchar(1),
+ primary key (modelID, subject, predicate, object,
+ l_language, l_datatype))');
- $this->dbConn->execute('CREATE INDEX nGS_idx1 ON datasets (datasetName)');
+ $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
+ $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject)');
+ $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate)');
+ $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object)');
+ $this->dbConn->execute('CREATE TABLE namespaces
+ (modelID long,
+ namespace varchar,
+ prefix varchar,
+ primary key (modelID, namespace, prefix))');
- $this->dbConn->execute("CREATE TABLE `dataset_model` (
- datasetName varchar,
- modelId long,
- graphURI varchar,
- PRIMARY KEY (modelId,datasetName))");
+ $this->dbConn->execute('CREATE INDEX n_name_idx ON namespaces (namespace)');
+ $this->dbConn->execute('CREATE INDEX n_pref_idx ON namespaces (prefix)');
+ $this->dbConn->execute("CREATE TABLE datasets
+ (datasetName varchar,
+ defaultModelUri varchar,
+ primary key (datasetName))");
- if (!$this->dbConn->completeTrans())
- echo $this->dbConn->errorMsg();
- }
+ $this->dbConn->execute('CREATE INDEX nGS_idx1 ON datasets (datasetName)');
-/**
- * Create tables and indexes for MySQL database
- *
- * @throws SqlError
- * @access private
- */
- function _createTables_MySql() {
+ $this->dbConn->execute("CREATE TABLE `dataset_model` (
+ datasetName varchar,
+ modelId long,
+ graphURI varchar,
+ PRIMARY KEY (modelId,datasetName))");
- $this->dbConn->startTrans();
- $this->dbConn->execute("CREATE TABLE models
- (modelID bigint NOT NULL,
- modelURI varchar(255) NOT NULL,
- baseURI varchar(255) DEFAULT '',
- primary key (modelID))");
+ if (!$this->dbConn->completeTrans()) {
+ throw new Exception($this->dbConn->errorMsg());
+ }
+ return true;
+ }
- $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
- $this->dbConn->execute("CREATE TABLE statements
- (modelID bigint NOT NULL,
- subject varchar(255) NOT NULL,
- predicate varchar(255) NOT NULL,
- object text,
- l_language varchar(255) DEFAULT '',
- l_datatype varchar(255) DEFAULT '',
- subject_is varchar(1) NOT NULL,
- object_is varchar(1) NOT NULL)");
- $this->dbConn->execute("CREATE TABLE namespaces
- (modelID bigint NOT NULL,
- namespace varchar(255) NOT NULL,
- prefix varchar(255) NOT NULL,
- primary key (modelID,namespace))");
+ /**
+ * Create tables and indexes for MySQL database
+ *
+ * @return boolean true If all is ok
+ *
+ * @throws Exception
+ */
+ function _createTables_MySQL()
+ {
- $this->dbConn->execute("CREATE TABLE `dataset_model` (
- `datasetName` varchar(255) NOT NULL default '0',
- `modelId` bigint(20) NOT NULL default '0',
- `graphURI` varchar(255) NOT NULL default '',
- PRIMARY KEY (`modelId`,`datasetName`))");
+ $this->dbConn->startTrans();
- $this->dbConn->execute("CREATE TABLE `datasets` (
- `datasetName` varchar(255) NOT NULL default '',
- `defaultModelUri` varchar(255) NOT NULL default '0',
- PRIMARY KEY (`datasetName`),
- KEY `datasetName` (`datasetName`))");
+ $this->dbConn->execute("CREATE TABLE models
+ (modelID bigint NOT NULL,
+ modelURI varchar(255) NOT NULL,
+ baseURI varchar(255) DEFAULT '',
+ primary key (modelID))");
- $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
- $this->dbConn->execute('CREATE INDEX n_mod_idx ON namespaces (modelID)');
+ $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
- $this->dbConn->execute('CREATE INDEX s_sub_pred_idx ON statements
- (subject(200),predicate(200))');
+ $this->dbConn->execute("CREATE TABLE statements
+ (modelID bigint NOT NULL,
+ subject varchar(255) NOT NULL,
+ predicate varchar(255) NOT NULL,
+ object text,
+ l_language varchar(255) DEFAULT '',
+ l_datatype varchar(255) DEFAULT '',
+ subject_is varchar(1) NOT NULL,
+ object_is varchar(1) NOT NULL)");
- $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject(200))');
- $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate(200))');
- $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object(250))');
+ $this->dbConn->execute("CREATE TABLE namespaces
+ (modelID bigint NOT NULL,
+ namespace varchar(255) NOT NULL,
+ prefix varchar(255) NOT NULL,
+ primary key (modelID,namespace))");
- $this->dbConn->execute('CREATE FULLTEXT INDEX s_obj_ftidx ON statements (object)');
+ $this->dbConn->execute("CREATE TABLE `dataset_model` (
+ `datasetName` varchar(255) NOT NULL default '0',
+ `modelId` bigint(20) NOT NULL default '0',
+ `graphURI` varchar(255) NOT NULL default '',
+ PRIMARY KEY (`modelId`,`datasetName`))");
- if (!$this->dbConn->completeTrans())
- echo $this->dbConn->errorMsg();
- }
+ $this->dbConn->execute("CREATE TABLE `datasets` (
+ `datasetName` varchar(255) NOT NULL default '',
+ `defaultModelUri` varchar(255) NOT NULL default '0',
+ PRIMARY KEY (`datasetName`),
+ KEY `datasetName` (`datasetName`))");
- /**
- * Create tables and indexes for MSSQL database
- *
- * @throws SqlError
- * @access private
- */
- function _createTables_mssql(){
+ $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
+ $this->dbConn->execute('CREATE INDEX n_mod_idx ON namespaces (modelID)');
- $this->dbConn->startTrans();
+ $this->dbConn->execute('CREATE INDEX s_sub_pred_idx ON statements
+ (subject(200),predicate(200))');
- $this->dbConn->execute("CREATE TABLE [dbo].[models] (
- [modelID] [int] NOT NULL ,
- [modelURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [baseURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
- ) ON [PRIMARY]");
+ $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject(200))');
+ $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate(200))');
+ $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object(250))');
- $this->dbConn->execute("CREATE TABLE [dbo].[statements] (
- [modelID] [int] NOT NULL ,
- [subject] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [predicate] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [object] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [l_language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [l_datatype] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [subject_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- [object_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]");
+ $this->dbConn->execute('CREATE FULLTEXT INDEX s_obj_ftidx ON statements (object)');
+ if (!$this->dbConn->completeTrans()) {
+ throw new Exception($this->dbConn->errorMsg());
+ }
+ return true;
+ }
- $this->dbConn->execute("CREATE TABLE [dbo].[namespaces] (
- [modelID] [int] NOT NULL ,
- [namespace] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
- [prefix] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
- ) ON [PRIMARY]");
- $this->dbConn->execute("ALTER TABLE [dbo].[models] WITH NOCHECK ADD
- CONSTRAINT [PK_models] PRIMARY KEY CLUSTERED
- (
- [modelID]
- ) ON [PRIMARY] ");
- $this->dbConn->execute("ALTER TABLE [dbo].[namespaces] WITH NOCHECK ADD
- CONSTRAINT [PK_namespaces] PRIMARY KEY CLUSTERED
- (
- [modelID],[namespace]
- ) ON [PRIMARY] ");
- $this->dbConn->execute("CREATE INDEX [joint index on subject and predicate] ON [dbo].[statements]([subject], [predicate]) ON [PRIMARY]");
+ /**
+ * Create tables and indexes for MSSQL database
+ *
+ * @return boolean true If all is ok
+ *
+ * @throws Exception
+ */
+ function _createTables_MSSQL()
+ {
+ $this->dbConn->startTrans();
+ $this->dbConn->execute("CREATE TABLE [dbo].[models] (
+ [modelID] [int] NOT NULL ,
+ [modelURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [baseURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
+ ) ON [PRIMARY]");
- if (!$this->dbConn->completeTrans())
- echo $this->dbConn->errorMsg();
+ $this->dbConn->execute("CREATE TABLE [dbo].[statements] (
+ [modelID] [int] NOT NULL ,
+ [subject] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [predicate] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [object] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [l_language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [l_datatype] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [subject_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ [object_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
+ ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]");
- }
+ $this->dbConn->execute("CREATE TABLE [dbo].[namespaces] (
+ [modelID] [int] NOT NULL ,
+ [namespace] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
+ [prefix] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+ ) ON [PRIMARY]");
- /**
- * Checks if tables are setup for RAP
- *
- * @param string $databaseType
- * @throws SqlError
- * @access public
- **/
- function isSetup($databaseType="MySQL") {
- if ($databaseType=="MySQL")
- return $this->_isSetup_MySql();
- if ($databaseType=="MSSQL")
- return $this->_isSetup_MSSQL();
- else {
- if ($databaseType=='MsAccess'){
- return $this->_isSetup_MsAccess();
- }else{
- $errmsg=RDFAPI_ERROR."(class: DbStore; method isSetup('$databaseType')):\nCurrently only MySQL, MsAccess and MSSQL are supported!";
- trigger_error($errmsg, E_USER_ERROR);}
- }
- }
+ $this->dbConn->execute("ALTER TABLE [dbo].[models] WITH NOCHECK ADD
+ CONSTRAINT [PK_models] PRIMARY KEY CLUSTERED
+ (
+ [modelID]
+ ) ON [PRIMARY] ");
+ $this->dbConn->execute("ALTER TABLE [dbo].[namespaces] WITH NOCHECK ADD
+ CONSTRAINT [PK_namespaces] PRIMARY KEY CLUSTERED
+ (
+ [modelID],[namespace]
+ ) ON [PRIMARY] ");
+ $this->dbConn->execute("CREATE INDEX [joint index on subject and predicate] ON [dbo].[statements]([subject], [predicate]) ON [PRIMARY]");
+
+
+ if (!$this->dbConn->completeTrans()) {
+ throw new Exception($this->dbConn->errorMsg());
+ }
+ return true;
+ }
+
+
+
+ /**
+ * Checks if tables are setup for RAP
+ *
+ * @param string $databaseType
+ * @throws Exception If database type is unsupported
+ * @access public
+ **/
+ public function isSetup($databaseType = null)
+ {
+ $driver = $this->getDriver($databaseType);
+ $this->assertDriverSupported($driver);
+
+ $issetupFunc = '_isSetup_' . $driver;
+ return $this->$issetupFunc();
+ }//public function isSetup($databaseType="MySQL")
+
+
+
+ /**
+ * Returns the driver for the database type.
+ * You can pass NULL or omit the parameter to
+ * use the parameter from the dbstore constructor
+ *
+ * @return string Database driver string
+ */
+ protected function getDriver($databaseType = null)
+ {
+ if ($databaseType === null) {
+ if ($this->driver === null) {
+ //backward compatibility
+ $databaseType = 'MySQL';
+ } else {
+ $databaseType = $this->driver;
+ }
+ }
+ return $databaseType;
+ }//protected function getDriver($databaseType = null)
+
+
+
+ /**
+ * Checks if the given driver is supported and throws an
+ * Exception if not.
+ *
+ * @param string $databaseType Database driver name (e.g. MySQL)
+ *
+ * @return true If it does not fail
+ *
+ * @throws Exception If the driver is not supported
+ */
+ protected function assertDriverSupported($databaseType)
+ {
+ if (!in_array($databaseType, self::$arSupportedDbTypes)) {
+ throw new Exception(
+ 'Unsupported database type, only supported: '
+ . implode(', ', self::$arSupportedDbTypes)
+ );
+ }
+ return true;
+ }//protected function assertDriverSupported($databaseType)
+
+
+
/**
* Checks if tables are setup for RAP (MySql)
*
Added: trunk/rdfapi-php/test/setup.php
===================================================================
--- trunk/rdfapi-php/test/setup.php (rev 0)
+++ trunk/rdfapi-php/test/setup.php 2007-10-09 15:48:01 UTC (rev 541)
@@ -0,0 +1,54 @@
+<?php
+/**
+* Prepares your system for RAP.
+* Creates database tables if they don't exist yet
+*/
+
+$strConfFile = dirname(__FILE__) . '/config.php';
+if (!file_exists($strConfFile)) {
+ die('Please copy "test/config.php.dist" to "test/config.php" and adjust it');
+}
+require_once $strConfFile;
+require_once RDFAPI_INCLUDE_DIR . '/model/ModelFactory.php';
+
+
+
+try {
+ $database = ModelFactory::getDbStore(
+ $GLOBALS['dbConf']['type'], $GLOBALS['dbConf']['host'],
+ $GLOBALS['dbConf']['database'], $GLOBALS['dbConf']['user'],
+ $GLOBALS['dbConf']['password']
+ );
+} catch (Exception $e) {
+ echo "Error: " . $e->getMessage() . "\n";
+ echo "Maybe the database '" . $GLOBALS['dbConf']['database'] . "' does not exist?\n";
+ exit(3);
+}
+
+if ($database->isSetup()) {
+ echo "Database is already setup.\n";
+ exit(0);
+}
+
+try {
+ $database->createTables();
+} catch (Exception $e) {
+ //mysql doesn't complete the transaction but is ok
+ if ($e->getMessage() != '') {
+ echo "Error: " . $e->getMessage() . "\n";
+ echo "Something failed when creating the tables\n";
+ exit(2);
+ }
+}
+
+
+if ($database->isSetup()) {
+ echo "Database has been setup.\n";
+ exit(0);
+} else {
+ echo "Database tables have been created, but somehow it still\n"
+ . " setup is incomplete. File a bug\n";
+ exit(1);
+}
+
+?>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-10-09 15:54:29
|
Revision: 542
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=542&view=rev
Author: cweiske
Date: 2007-10-09 08:54:27 -0700 (Tue, 09 Oct 2007)
Log Message:
-----------
Tell explicitely that the driver type is wrong
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbStore.php
trunk/rdfapi-php/test/setup.php
Modified: trunk/rdfapi-php/api/model/DbStore.php
===================================================================
--- trunk/rdfapi-php/api/model/DbStore.php 2007-10-09 15:48:01 UTC (rev 541)
+++ trunk/rdfapi-php/api/model/DbStore.php 2007-10-09 15:54:27 UTC (rev 542)
@@ -309,7 +309,7 @@
public function createTables($databaseType = null)
{
$driver = $this->getDriver($databaseType);
- $this->assertDriverSupported($driver);
+ self::assertDriverSupported($driver);
$createFunc = '_createTables_' . $driver;
return $this->$createFunc();
@@ -519,7 +519,7 @@
public function isSetup($databaseType = null)
{
$driver = $this->getDriver($databaseType);
- $this->assertDriverSupported($driver);
+ self::assertDriverSupported($driver);
$issetupFunc = '_isSetup_' . $driver;
return $this->$issetupFunc();
@@ -559,7 +559,7 @@
*
* @throws Exception If the driver is not supported
*/
- protected function assertDriverSupported($databaseType)
+ public static function assertDriverSupported($databaseType)
{
if (!in_array($databaseType, self::$arSupportedDbTypes)) {
throw new Exception(
@@ -568,7 +568,7 @@
);
}
return true;
- }//protected function assertDriverSupported($databaseType)
+ }//public static function assertDriverSupported($databaseType)
Modified: trunk/rdfapi-php/test/setup.php
===================================================================
--- trunk/rdfapi-php/test/setup.php 2007-10-09 15:48:01 UTC (rev 541)
+++ trunk/rdfapi-php/test/setup.php 2007-10-09 15:54:27 UTC (rev 542)
@@ -9,10 +9,19 @@
die('Please copy "test/config.php.dist" to "test/config.php" and adjust it');
}
require_once $strConfFile;
+require_once RDFAPI_INCLUDE_DIR . '/model/DbStore.php';
require_once RDFAPI_INCLUDE_DIR . '/model/ModelFactory.php';
+try {
+ DbStore::assertDriverSupported($GLOBALS['dbConf']['type']);
+} catch (Exception $e) {
+ echo "Error: " . $e->getMessage() . "\n";
+ echo "Be sure to write the driver type in the same cAsE\n";
+ exit(4);
+}
+
try {
$database = ModelFactory::getDbStore(
$GLOBALS['dbConf']['type'], $GLOBALS['dbConf']['host'],
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <cw...@us...> - 2007-10-10 17:41:16
|
Revision: 545
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=545&view=rev
Author: cweiske
Date: 2007-10-10 10:41:15 -0700 (Wed, 10 Oct 2007)
Log Message:
-----------
- Support MySQLi (link to MySQL methods)
- Fix wrong cAsE in database drivers
Modified Paths:
--------------
trunk/rdfapi-php/api/model/DbStore.php
trunk/rdfapi-php/test/setup.php
Modified: trunk/rdfapi-php/api/model/DbStore.php
===================================================================
--- trunk/rdfapi-php/api/model/DbStore.php 2007-10-09 16:24:08 UTC (rev 544)
+++ trunk/rdfapi-php/api/model/DbStore.php 2007-10-10 17:41:15 UTC (rev 545)
@@ -35,6 +35,7 @@
*/
public static $arSupportedDbTypes = array(
"MySQL",
+ "MySQLi",
"MSSQL",
'MsAccess'
);
@@ -453,6 +454,16 @@
/**
+ * Creates tables on a MySQLi database
+ */
+ function _createTables_MySQLi()
+ {
+ return $this->_createTables_MySQL();
+ }//function _createTables_MySQLi()
+
+
+
+ /**
* Create tables and indexes for MSSQL database
*
* @return boolean true If all is ok
@@ -481,7 +492,7 @@
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]");
- $this->dbConn->execute("CREATE TABLE [dbo].[namespaces] (
+ $this->dbConn->execute("CREATE TABLE [dbo].[namespaces] (
[modelID] [int] NOT NULL ,
[namespace] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[prefix] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
@@ -532,9 +543,11 @@
* You can pass NULL or omit the parameter to
* use the parameter from the dbstore constructor
*
- * @return string Database driver string
+ * @param string $databaseType Database driver name (e.g. MySQL)
+ *
+ * @return string Database driver string (e.g. MySQL)
*/
- protected function getDriver($databaseType = null)
+ public function getDriver($databaseType = null)
{
if ($databaseType === null) {
if ($this->driver === null) {
@@ -544,12 +557,32 @@
$databaseType = $this->driver;
}
}
+ if (!self::isDriverSupported($databaseType)) {
+ //check if it is a known driver in wrong case
+ $arLowercases = array_map('strtolower', self::$arSupportedDbTypes);
+ $arMapping = array_combine($arLowercases, self::$arSupportedDbTypes);
+ if (isset($arMapping[strtolower($databaseType)])) {
+ $databaseType = $arMapping[strtolower($databaseType)];
+ }
+ }
return $databaseType;
- }//protected function getDriver($databaseType = null)
+ }//public function getDriver($databaseType = null)
/**
+ * Returns if the given driver is supported
+ *
+ * @return boolean True if it supported, false if not
+ */
+ public static function isDriverSupported($databaseType)
+ {
+ return in_array($databaseType, self::$arSupportedDbTypes);
+ }//public static function isDriverSupported($databaseType)
+
+
+
+ /**
* Checks if the given driver is supported and throws an
* Exception if not.
*
@@ -561,7 +594,7 @@
*/
public static function assertDriverSupported($databaseType)
{
- if (!in_array($databaseType, self::$arSupportedDbTypes)) {
+ if (!self::isDriverSupported($databaseType)) {
throw new Exception(
'Unsupported database type, only supported: '
. implode(', ', self::$arSupportedDbTypes)
@@ -572,69 +605,99 @@
- /**
- * Checks if tables are setup for RAP (MySql)
- *
- * @throws SqlError
- * @access private
- **/
- function _isSetup_MySql() {
- $recordSet =& $this->dbConn->execute("SHOW TABLES");
- if (!$recordSet)
- echo $this->dbConn->errorMsg();
- else {
- $tables = array();
- while (!$recordSet->EOF) {
+ /**
+ * Checks if tables are setup for RAP (MySql)
+ *
+ * @throws SqlError
+ * @access private
+ **/
+ function _isSetup_MySQL()
+ {
+ $recordSet =& $this->dbConn->execute("SHOW TABLES");
+ if (!$recordSet) {
+ throw new Exception($this->dbConn->errorMsg());
+ } else {
+ $tables = array();
+ while (!$recordSet->EOF) {
+ $tables[]= $recordSet->fields[0];
+ if (isset($i)) {
+ ++$i;
+ }
+ $recordSet->moveNext();
+ }
+ if (in_array("models",$tables) && in_array("statements",$tables)
+ && in_array("namespaces",$tables)) {
+ return true;
+ }
+ }
+ return false;
+ }//function _isSetup_MySQL()
- $tables[]= $recordSet->fields[0];
- if(isset($i)){++$i;}
- $recordSet->moveNext();
- }
- if (in_array("models",$tables) && in_array("statements",$tables)&& in_array("namespaces",$tables)) return true;
- }
- return false;
- }
+ /**
+ * Checks if tables are setup for RAP (MySQLi)
+ *
+ * @see _isSetup_MySQL()
+ */
+ function _isSetup_MySQLi()
+ {
+ return $this->_isSetup_MySQL();
+ }//function _isSetup_MySQLi()
- /**
- * Checks if tables are setup for RAP (MsAccess)
- *
- * @throws SqlError
- * @access private
- **/
- function _isSetup_MsAccess() {
- $tables =& $this->dbConn->MetaTables();
- if (!$tables)
- echo $this->dbConn->errorMsg();
- if (count($tables)==0){
- return false;}
- else {
- if (in_array("models",$tables) && in_array("statements",$tables) && in_array("namespaces",$tables)){ return true;
- }else{return false;}
- }
- }
- /**
- * Checks if tables are setup for RAP (MSSQL)
- *
- * @throws SqlError
- * @access private
- **/
- function _isSetup_MSSQL() {
- $tables =& $this->dbConn->MetaTables();
- if (!$tables)
- echo $this->dbConn->errorMsg();
- if (count($tables)==0){
- return false;}
- else {
- if (in_array("models",$tables) && in_array("statements",$tables) && in_array("namespaces",$tables)){ return true;
- }else{return false;}
- }
- }
+ /**
+ * Checks if tables are setup for RAP (MsAccess)
+ *
+ * @throws SqlError
+ * @access private
+ **/
+ function _isSetup_MsAccess()
+ {
+ $tables =& $this->dbConn->MetaTables();
+ if (!$tables) {
+ throw new Exception($this->dbConn->errorMsg());
+ }
+ if (count($tables) == 0) {
+ return false;
+ } else {
+ if (in_array("models",$tables) && in_array("statements",$tables)
+ && in_array("namespaces",$tables)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }//function _isSetup_MsAccess()
+
+ /**
+ * Checks if tables are setup for RAP (MSSQL)
+ *
+ * @throws SqlError
+ * @access private
+ **/
+ function _isSetup_MSSQL()
+ {
+ $tables =& $this->dbConn->MetaTables();
+ if (!$tables) {
+ throw new Exception($this->dbConn->errorMsg());
+ }
+ if (count($tables) == 0) {
+ return false;
+ } else {
+ if (in_array("models",$tables) && in_array("statements",$tables)
+ && in_array("namespaces",$tables)){
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }//function _isSetup_MSSQL()
+
+
/**
* Create a new instance of DatasetDb with the given $datasetName
* and insert the DatasetDb variables into the database.
Modified: trunk/rdfapi-php/test/setup.php
===================================================================
--- trunk/rdfapi-php/test/setup.php 2007-10-09 16:24:08 UTC (rev 544)
+++ trunk/rdfapi-php/test/setup.php 2007-10-10 17:41:15 UTC (rev 545)
@@ -13,7 +13,8 @@
require_once RDFAPI_INCLUDE_DIR . '/model/ModelFactory.php';
try {
- DbStore::assertDriverSupported($GLOBALS['dbConf']['type']);
+ $type = DbStore::getDriver($GLOBALS['dbConf']['type']);
+ DbStore::assertDriverSupported($type);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
echo "Be sure to write the driver type in the same cAsE\n";
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <p_f...@us...> - 2007-11-14 09:45:43
|
Revision: 547
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=547&view=rev
Author: p_frischmuth
Date: 2007-11-14 01:45:39 -0800 (Wed, 14 Nov 2007)
Log Message:
-----------
[added] initial version of a json parser
[added] loadFromString method in Model class, in order to easily load statements from strings (yet only json is supported)
[added] test class for new json parser and initial test routine
[modified] added constant PACKAGE_SYNTAX_JSON to constants.php
[added] SyntaxJSON package in order to load json parser dynamically
[propset] added svn:keywords for new file (Id)
Modified Paths:
--------------
trunk/rdfapi-php/api/constants.php
trunk/rdfapi-php/api/model/Model.php
Added Paths:
-----------
trunk/rdfapi-php/api/syntax/JsonParser.php
trunk/rdfapi-php/api/syntax/SyntaxJSON.php
trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php
Modified: trunk/rdfapi-php/api/constants.php
===================================================================
--- trunk/rdfapi-php/api/constants.php 2007-11-06 14:26:06 UTC (rev 546)
+++ trunk/rdfapi-php/api/constants.php 2007-11-14 09:45:39 UTC (rev 547)
@@ -31,6 +31,7 @@
define('PACKAGE_DBASE','model/DBase.php');
define('PACKAGE_SYNTAX_RDF','syntax/SyntaxRDF.php');
define('PACKAGE_SYNTAX_N3','syntax/SyntaxN3.php');
+define('PACKAGE_SYNTAX_JSON','syntax/SyntaxJSON.php');
define('PACKAGE_SYNTAX_GRDDL','syntax/SyntaxGRDDL.php');
define('PACKAGE_VOCABULARY','vocabulary/Vocabulary.php');
define('PACKAGE_RDQL','rdql/RDQL.php');
Modified: trunk/rdfapi-php/api/model/Model.php
===================================================================
--- trunk/rdfapi-php/api/model/Model.php 2007-11-06 14:26:06 UTC (rev 546)
+++ trunk/rdfapi-php/api/model/Model.php 2007-11-14 09:45:39 UTC (rev 547)
@@ -133,8 +133,27 @@
$this->setBaseURI($temp->getBaseURI());
}
+ /**
+ * This method takes a string conatining data and adds the parsed data to this model.
+ *
+ * @param string $str The string containing the data to be parsed and loaded.
+ * @param type $type The type of the string, currently only 'json' is supported.
+ */
+ function loadFromString($str, $type) {
+
+ switch ($type) {
+ case 'json':
+ include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_JSON);
+ $parser = new JsonParser();
+ break;
+ default:
+ trigger_error('(class: Model; method: loadFromString): type ' . $type . 'is currently not supported',
+ E_USER_ERROR);
+ }
+
+ $parser->generateModelFromString($str, $this);
+ }
-
/**
* Adds a statement from another model to this model.
* If the statement to be added contains a blankNode with an identifier
Added: trunk/rdfapi-php/api/syntax/JsonParser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/JsonParser.php (rev 0)
+++ trunk/rdfapi-php/api/syntax/JsonParser.php 2007-11-14 09:45:39 UTC (rev 547)
@@ -0,0 +1,52 @@
+<?php
+/**
+ * This class provides capabilities to parse json encoded rdf models.
+ *
+ * @package syntax
+ * @author Philipp Frischmuth <ph...@fr...>
+ * @version $Id$
+ */
+class JsonParser extends Object {
+
+ /**
+ * This method takes a json encoded rdf-model and a reference to aa (usually empty) MemModel, parses the json
+ * string and adds the statements to the given MemModel.
+ *
+ * @param string $jsonString The string that contains the rdf model, encoded as a json-string.
+ * @param MemModel $model A reference to the model, where to add the statements, usually an empty MemModel.
+ */
+ public function generateModelFromString($jsonString, $model) {
+
+ $jsonModel = array();
+ $jsonModel = json_decode($jsonString, true);
+
+ // throws an excpetion if json model was corrupt
+ if (!is_array($jsonModel)) {
+ throw new Exception('error in json string');
+ }
+
+ foreach ($jsonModel as $subject=>$remain) {
+ foreach ($remain as $predicate=>$object) {
+ $s = (strpos($subject, '_') === 0) ? new BlankNode(substr($subject, 2)) : new Resource($subject);
+ $p = new Resource($predicate);
+
+ foreach ($object as $obj) {
+ if ($obj['type'] === 'uri') {
+ $o = new Resource($obj['value']);
+ } else if ($obj['type'] === 'bnode') {
+ $o = new BlankNode(substr($obj['value'], 2));
+ } else {
+ $dtype = (isset($obj['datatype'])) ? $obj['datatype'] : '';
+ $lang = (isset($obj['lang'])) ? $obj['lang'] : '';
+
+ $o = new Literal($obj['value'], $lang);
+ $o->setDatatype($dtype);
+ }
+
+ $model->add(new Statement($s, $p, $o));
+ }
+ }
+ }
+ }
+}
+?>
Property changes on: trunk/rdfapi-php/api/syntax/JsonParser.php
___________________________________________________________________
Name: svn:keywords
+ Id
Added: trunk/rdfapi-php/api/syntax/SyntaxJSON.php
===================================================================
--- trunk/rdfapi-php/api/syntax/SyntaxJSON.php (rev 0)
+++ trunk/rdfapi-php/api/syntax/SyntaxJSON.php 2007-11-14 09:45:39 UTC (rev 547)
@@ -0,0 +1,5 @@
+<?php
+// Include Syntax classes
+// $Id$
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/JsonParser.php' );
+?>
\ No newline at end of file
Property changes on: trunk/rdfapi-php/api/syntax/SyntaxJSON.php
___________________________________________________________________
Name: svn:keywords
+ Id
Added: trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php (rev 0)
+++ trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php 2007-11-14 09:45:39 UTC (rev 547)
@@ -0,0 +1,119 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_JSON;
+/**
+ * Tests the JsonParser
+ *
+ * @version $Id $
+ * @author Philipp Frischmuth <ph...@fr...>
+ *
+ * @package unittests
+ * @access public
+ */
+
+class testJsonParser extends UnitTestCase
+{
+ var $modelString;
+
+ function testJsonParser() {
+ $this->UnitTestCase();
+
+ GLOBAL $short_datatype;
+
+ $this->modelString = '{ "http://example.org/about" : {
+ "http://purl.org/dc/elements/1.1/creator" : [
+ {
+ "value" : "Anna Wilder",
+ "type" : "literal"
+ }
+ ],
+ "http://purl.org/dc/elements/1.1/title" : [
+ {
+ "value" : "Annas Homepage",
+ "type" : "literal",
+ "lang" : "en"
+ }
+ ],
+ "http://xmlns.com/foaf/0.1/maker" : [
+ {
+ "value" : "_:person",
+ "type" : "bnode"
+ }
+ ],
+ "http://purl.org/dc/elements/1.1/title2" : [
+ {
+ "value" : "Anns HP",
+ "type" : "literal",
+ "lang" : "en",
+ "datatype" : "' . $short_datatype['STRING'] . '"
+ }
+ ]
+ },
+ "_:person" : {
+ "http://xmlns.com/foaf/0.1/homepage" : [
+ {
+ "value" : "http://example.org/about",
+ "type" : "uri"
+ }
+ ]
+ }}';
+ }
+
+ function testGenerateModelFromString() {
+
+ $parser = new JsonParser();
+ $model = new MemModel('http://example.com/');
+
+ try {
+ $parser->generateModelFromString($this->modelString, $model);
+ } catch (Exception $e) {
+ $this->fail($e->getMessage());
+ }
+
+ GLOBAL $short_datatype;
+ $model2 = new MemModel('http://example.com/');
+
+ // Ceate new statements and add them to the model
+ $statement1 = new Statement(new Resource('http://example.org/about'),
+ new Resource('http://purl.org/dc/elements/1.1/creator'),
+ new Literal('Anna Wilder'));
+
+ $statement2 = new Statement(new Resource('http://example.org/about'),
+ new Resource("http://purl.org/dc/elements/1.1/title"),
+ new Literal('Annas Homepage', 'en'));
+
+ $statement3 = new Statement(new Resource('http://example.org/about'),
+ new Resource('http://xmlns.com/foaf/0.1/maker'),
+ new BlankNode('person'));
+
+ $statement4 = new Statement(new BlankNode('person'),
+ new Resource("http://xmlns.com/foaf/0.1/homepage"),
+ new Resource('http://example.org/about'));
+
+ $statement5 = new Statement(new Resource('http://example.org/about'),
+ new Resource("http://purl.org/dc/elements/1.1/title2"),
+ new Literal('Anns HP', 'en', $short_datatype['STRING']));
+
+ $statement6 = new Statement(new Resource('http://example.org/about'),
+ new Resource("http://purl.org/dc/elements/1.1/title2"),
+ new Literal('Anns HP', 'en', $short_datatype['INTEGER']));
+
+
+ $model2->add($statement1);
+ $model2->add($statement2);
+ $model2->add($statement3);
+ $model2->add($statement4);
+ $model2->add($statement5);
+
+ $this->assertTrue($model->containsAll($model2));
+
+ $model2->remove($statement5);
+ $model2->add($statement6);
+
+ $this->assertFalse($model->containsAll($model2));
+
+#echo "<pre>";
+#print_r($model2);
+#echo "</pre>";
+ }
+}
+?>
Property changes on: trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php
___________________________________________________________________
Name: svn:keywords
+ Id
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <p_f...@us...> - 2007-11-23 09:12:14
|
Revision: 552
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=552&view=rev
Author: p_frischmuth
Date: 2007-11-23 01:12:11 -0800 (Fri, 23 Nov 2007)
Log Message:
-----------
[added] a serializer class for rdf/json format
[added] a unit test class for the json serializer in order to test the serialize method
[propset] set svn:keyword Id on new files
[modified] added the new test classes to the allTest environment
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/SyntaxJSON.php
trunk/rdfapi-php/test/unit/allTests.php
Added Paths:
-----------
trunk/rdfapi-php/api/syntax/JsonSerializer.php
trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php
Added: trunk/rdfapi-php/api/syntax/JsonSerializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/JsonSerializer.php (rev 0)
+++ trunk/rdfapi-php/api/syntax/JsonSerializer.php 2007-11-23 09:12:11 UTC (rev 552)
@@ -0,0 +1,137 @@
+<?php
+/**
+ * This class provides capabilities to serialize MemModels to json strings.
+ *
+ * @package syntax
+ * @author Philipp Frischmuth <ph...@fr...>
+ * @version $Id:$
+ */
+class JsonSerializer extends Object {
+
+ /**
+ * This method takes a MemModel object ad parameter and serializes all contained triples to rdf/json format.
+ *
+ * @see http://n2.talis.com/wiki/RDF_JSON_Specification#rdf.2Fjson
+ * @param MemModel $model
+ * @return string Returns a string containing the serialized model.
+ */
+ public function serialize(MemModel $model) {
+
+ // create the root json object (root object)
+ $jsonString = '{';
+ $subjects = array();
+
+ // sort triples by subject
+ foreach ($model->triples as $triple) {
+ $subjects[$triple->toStringSubject()][] = $triple;
+ }
+
+ // sort alphabetically
+ ksort($subjects);
+
+ // echo '<pre>';
+ // print_r($subjects);
+ // echo '</pre>';
+
+ // triples are sorted by subject now, each key is a subject uri, containing all triples with this subject uri
+ $i = 0;
+ foreach ($subjects as $predicatesArray) {
+ $predicates = array();
+
+ if ($i > 0) {
+ $jsonString .= ',';
+ }
+ $i++;
+
+ $subj = $predicatesArray[0]->getSubject();
+
+ // add special _: sequence for blank node only
+ if ($subj instanceof BlankNode) {
+ $jsonString .= PHP_EOL . ' "_:' . $subj->getLabel() . '" : ';
+ } else {
+ $jsonString .= PHP_EOL . ' "' . $subj->getLabel() . '" : ';
+ }
+
+
+
+ // create a json object for each subject (subject object)
+ $jsonString .= '{';
+
+ // sort triples with current subject by predicate
+ foreach ($predicatesArray as $triple) {
+ $predicates[$triple->toStringPredicate()][] = $triple;
+ }
+
+ // sort alphabetically
+ ksort($predicates);
+
+ $j = 0;
+ foreach ($predicates as $valueArray) {
+
+ if ($j > 0) {
+ $jsonString .= ',';
+ }
+ $j++;
+
+ $jsonString .= PHP_EOL . ' "' . $valueArray[0]->getLabelPredicate() . '" : ';
+
+ // create a json array (value array)
+ $jsonString .= '[';
+
+ $k = 0;
+ foreach ($valueArray as $triple) {
+ if ($k > 0) {
+ $jsonString .= ',';
+ }
+ $k++;
+
+ // create json value object (value object)
+ $jsonString .= PHP_EOL . ' {';
+
+ $obj = $triple->getObject();
+
+ // add special _: sequence for blank nodes only
+ if ($obj instanceof BlankNode) {
+ $jsonString .= PHP_EOL . ' "value" : "_:' . $obj->getLabel() . '",';
+ } else {
+ $jsonString .= PHP_EOL . ' "value" : "' . $obj->getLabel() . '",';
+ }
+
+ // add type of object
+ if ($obj instanceof Literal) {
+ $jsonString .= PHP_EOL . ' "type" : "literal"';
+ } else if ($obj instanceof BlankNode) {
+ $jsonString .= PHP_EOL . ' "type" : "bnode"';
+ } else {
+ $jsonString .= PHP_EOL . ' "type" : "uri"';
+ }
+
+ if ($obj instanceof Literal) {
+ if ($obj->getLanguage() != '') {
+ $jsonString .= ',' . PHP_EOL . ' "lang" : "' . $obj->getLanguage() . '"';
+ }
+ if ($obj->getDatatype() != '') {
+ $jsonString .= ',' . PHP_EOL . ' "datatype" : "' . $obj->getDatatype() . '"';
+ }
+
+ }
+
+ // close value object
+ $jsonString .= PHP_EOL . ' }';
+ }
+
+ // close the value array
+ $jsonString .= PHP_EOL . ' ]';
+ }
+
+ // close the json object (for the subject) (subject object)
+ $jsonString .= PHP_EOL . ' }';
+ }
+
+ // close root json object (root object)
+ $jsonString .= PHP_EOL . '}';
+
+ return $jsonString;
+ }
+}
+?>
Property changes on: trunk/rdfapi-php/api/syntax/JsonSerializer.php
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: trunk/rdfapi-php/api/syntax/SyntaxJSON.php
===================================================================
--- trunk/rdfapi-php/api/syntax/SyntaxJSON.php 2007-11-22 19:58:35 UTC (rev 551)
+++ trunk/rdfapi-php/api/syntax/SyntaxJSON.php 2007-11-23 09:12:11 UTC (rev 552)
@@ -2,4 +2,5 @@
// Include Syntax classes
// $Id$
require_once( RDFAPI_INCLUDE_DIR . 'syntax/JsonParser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/JsonSerializer.php' );
?>
\ No newline at end of file
Added: trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php (rev 0)
+++ trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php 2007-11-23 09:12:11 UTC (rev 552)
@@ -0,0 +1,57 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_JSON;
+/**
+ * Tests the JsonSerializer
+ *
+ * @version $Id $
+ * @author Philipp Frischmuth <ph...@fr...>
+ *
+ * @package unittests
+ * @access public
+ */
+class testJsonSerializer extends UnitTestCase {
+
+ var $model;
+
+ function testJsonSerializer() {
+
+ $this->model = new MemModel();
+
+ $res1 = new Resource('http://example.com/res1');
+ $res2 = new Resource('http://example.com/res2');
+ $res3 = new Resource('http://example.com/res3');
+
+ $bn1 = new BlankNode('test1');
+ $bn2 = new BlankNode('test2');
+
+ $literal1 = new Literal('test literal');
+ $literal2 = new Literal('test literal', 'en');
+ $literal3 = new Literal('test literal', 'de', 'http://www.w3.org/2001/XMLSchema#string');
+
+ $stm1 = new Statement($res1, $res2, $res3);
+ $stm2 = new Statement($res1, $res2, $bn1);
+ $stm3 = new Statement($res1, $res2, $literal1);
+ $stm4 = new Statement($res1, $res2, $literal2);
+ $stm5 = new Statement($res1, $res2, $literal3);
+ $stm6 = new Statement($bn1, $res2, $bn2);
+
+ $this->model->add($stm1);
+ $this->model->add($stm2);
+ $this->model->add($stm3);
+ $this->model->add($stm4);
+ $this->model->add($stm5);
+ $this->model->add($stm6);
+ }
+
+ function testSerialize() {
+
+ $ser = new JsonSerializer();
+
+ $jsonString = $ser->serialize($this->model);
+ $memModel = new MemModel();
+ $memModel->loadFromString($jsonString, 'json');
+
+ $this->assertTrue($this->model->equals($memModel));
+ }
+}
+?>
Property changes on: trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: trunk/rdfapi-php/test/unit/allTests.php
===================================================================
--- trunk/rdfapi-php/test/unit/allTests.php 2007-11-22 19:58:35 UTC (rev 551)
+++ trunk/rdfapi-php/test/unit/allTests.php 2007-11-23 09:12:11 UTC (rev 552)
@@ -119,6 +119,8 @@
$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Syntax/n3Serializer_test.php');
$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Syntax/rdf_Parser_tests.php');
$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Syntax/rdf_Serializer_tests.php');
+$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Syntax/jsonParser_test.php');
+$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/Syntax/jsonSerializer_test.php');
//$test_syntax->addTestFile(RDFAPI_TEST_INCLUDE_DIR. 'test/unit/rdf/rdf_test_cases.php');
$test_syntax->run(new $runnerClass());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <p_f...@us...> - 2007-12-11 20:27:38
|
Revision: 555
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=555&view=rev
Author: p_frischmuth
Date: 2007-12-11 12:27:34 -0800 (Tue, 11 Dec 2007)
Log Message:
-----------
[fixed] removed all newlines and whitespaces in order to follow the json spec; escaped all forbidden chars (see json spec for details)
[modified] test cases updated in order to test special char cases
Modified Paths:
--------------
trunk/rdfapi-php/api/syntax/JsonParser.php
trunk/rdfapi-php/api/syntax/JsonSerializer.php
trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php
trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php
Modified: trunk/rdfapi-php/api/syntax/JsonParser.php
===================================================================
--- trunk/rdfapi-php/api/syntax/JsonParser.php 2007-12-05 08:18:50 UTC (rev 554)
+++ trunk/rdfapi-php/api/syntax/JsonParser.php 2007-12-11 20:27:34 UTC (rev 555)
@@ -19,7 +19,7 @@
$jsonModel = array();
$jsonModel = json_decode($jsonString, true);
-
+
// throws an excpetion if json model was corrupt
if (!is_array($jsonModel)) {
throw new Exception('error in json string');
@@ -39,7 +39,9 @@
$dtype = (isset($obj['datatype'])) ? $obj['datatype'] : '';
$lang = (isset($obj['lang'])) ? $obj['lang'] : '';
- $o = new Literal($obj['value'], $lang);
+ $oVal = $obj['value'];
+
+ $o = new Literal($oVal, $lang);
$o->setDatatype($dtype);
}
Modified: trunk/rdfapi-php/api/syntax/JsonSerializer.php
===================================================================
--- trunk/rdfapi-php/api/syntax/JsonSerializer.php 2007-12-05 08:18:50 UTC (rev 554)
+++ trunk/rdfapi-php/api/syntax/JsonSerializer.php 2007-12-11 20:27:34 UTC (rev 555)
@@ -4,7 +4,7 @@
*
* @package syntax
* @author Philipp Frischmuth <ph...@fr...>
- * @version $Id:$
+ * @version $Id$
*/
class JsonSerializer extends Object {
@@ -28,11 +28,7 @@
// sort alphabetically
ksort($subjects);
-
- // echo '<pre>';
- // print_r($subjects);
- // echo '</pre>';
-
+
// triples are sorted by subject now, each key is a subject uri, containing all triples with this subject uri
$i = 0;
foreach ($subjects as $predicatesArray) {
@@ -47,9 +43,9 @@
// add special _: sequence for blank node only
if ($subj instanceof BlankNode) {
- $jsonString .= PHP_EOL . ' "_:' . $subj->getLabel() . '" : ';
+ $jsonString .= '"_:' . $this->_escapeValue($subj->getLabel()) . '":';
} else {
- $jsonString .= PHP_EOL . ' "' . $subj->getLabel() . '" : ';
+ $jsonString .= '"' . $this->_escapeValue($subj->getLabel()) . '":';
}
@@ -73,7 +69,7 @@
}
$j++;
- $jsonString .= PHP_EOL . ' "' . $valueArray[0]->getLabelPredicate() . '" : ';
+ $jsonString .= '"' . $this->_escapeValue($valueArray[0]->getLabelPredicate()) . '":';
// create a json array (value array)
$jsonString .= '[';
@@ -86,52 +82,82 @@
$k++;
// create json value object (value object)
- $jsonString .= PHP_EOL . ' {';
+ $jsonString .= '{';
$obj = $triple->getObject();
// add special _: sequence for blank nodes only
if ($obj instanceof BlankNode) {
- $jsonString .= PHP_EOL . ' "value" : "_:' . $obj->getLabel() . '",';
+ $jsonString .= '"value":"_:' . $this->_escapeValue($obj->getLabel()) . '",';
+ } else if ($obj instanceof Literal) {
+ $jsonString .= '"value":"' . $this->_escapeValue($obj->getLabel()) . '",';
} else {
- $jsonString .= PHP_EOL . ' "value" : "' . $obj->getLabel() . '",';
+ $jsonString .= '"value":"' . $this->_escapeValue($obj->getLabel()) . '",';
}
// add type of object
if ($obj instanceof Literal) {
- $jsonString .= PHP_EOL . ' "type" : "literal"';
+ $jsonString .= '"type":"literal"';
} else if ($obj instanceof BlankNode) {
- $jsonString .= PHP_EOL . ' "type" : "bnode"';
+ $jsonString .= '"type":"bnode"';
} else {
- $jsonString .= PHP_EOL . ' "type" : "uri"';
+ $jsonString .= '"type":"uri"';
}
if ($obj instanceof Literal) {
if ($obj->getLanguage() != '') {
- $jsonString .= ',' . PHP_EOL . ' "lang" : "' . $obj->getLanguage() . '"';
+ $jsonString .= ',"lang":"' . $this->_escapeValue($obj->getLanguage()) . '"';
}
if ($obj->getDatatype() != '') {
- $jsonString .= ',' . PHP_EOL . ' "datatype" : "' . $obj->getDatatype() . '"';
+ $jsonString .= ',"datatype":"' . $this->_escapeValue($obj->getDatatype()) . '"';
}
}
// close value object
- $jsonString .= PHP_EOL . ' }';
+ $jsonString .= '}';
}
// close the value array
- $jsonString .= PHP_EOL . ' ]';
+ $jsonString .= ']';
}
// close the json object (for the subject) (subject object)
- $jsonString .= PHP_EOL . ' }';
+ $jsonString .= '}';
}
// close root json object (root object)
- $jsonString .= PHP_EOL . '}';
+ $jsonString .= '}';
return $jsonString;
}
+
+ /*
+ * Escapes the following chars as specified at json.org:
+ *
+ * " -> \"
+ * \ -> \\
+ * / -> \/
+ * \b -> \\b
+ * \f -> \\f
+ * \n -> \\n
+ * \r -> \\r
+ * \t -> \\t
+ * \uXXXX -> \\uXXXX
+ */
+ protected function _escapeValue($value) {
+
+
+ $value = str_replace("\\", '\\\\', $value);
+ #$value = str_replace("/", '\/', $value);
+ $value = str_replace("\n", '\\n', $value);
+ $value = str_replace("\t", '\\t', $value);
+ $value = str_replace("\r", '\\r', $value);
+ $value = str_replace("\b", '\\b', $value);
+ $value = str_replace("\f", '\\f', $value);
+ $value = str_replace('"', '\"', $value);
+
+ return $value;
+ }
}
?>
Modified: trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php 2007-12-05 08:18:50 UTC (rev 554)
+++ trunk/rdfapi-php/test/unit/Syntax/jsonParser_test.php 2007-12-11 20:27:34 UTC (rev 555)
@@ -19,43 +19,7 @@
GLOBAL $short_datatype;
- $this->modelString = '{ "http://example.org/about" : {
- "http://purl.org/dc/elements/1.1/creator" : [
- {
- "value" : "Anna Wilder",
- "type" : "literal"
- }
- ],
- "http://purl.org/dc/elements/1.1/title" : [
- {
- "value" : "Annas Homepage",
- "type" : "literal",
- "lang" : "en"
- }
- ],
- "http://xmlns.com/foaf/0.1/maker" : [
- {
- "value" : "_:person",
- "type" : "bnode"
- }
- ],
- "http://purl.org/dc/elements/1.1/title2" : [
- {
- "value" : "Anns HP",
- "type" : "literal",
- "lang" : "en",
- "datatype" : "' . $short_datatype['STRING'] . '"
- }
- ]
- },
- "_:person" : {
- "http://xmlns.com/foaf/0.1/homepage" : [
- {
- "value" : "http://example.org/about",
- "type" : "uri"
- }
- ]
- }}';
+ $this->modelString = '{"http://example.org/about":{"http://purl.org/dc/elements/1.1/creator":[{"value":"Anna Wilder","type":"literal"}],"http://purl.org/dc/elements/1.1/title":[{"value":"Annas Homepage","type":"literal","lang":"en"}],"http://xmlns.com/foaf/0.1/maker":[{"value":"_:person","type":"bnode"}],"http://purl.org/dc/elements/1.1/title2":[{"value":"Anns HP","type":"literal","lang":"en","datatype":"' . $short_datatype['STRING'] . '"}]},"_:person":{"http://xmlns.com/foaf/0.1/homepage":[{"value":"http://example.org/about","type":"uri"}],"http://example.com/testProp1":[{"value":"\\"double quote\\nnewline\\ttab\\rcarriage return\\\\reverse solidus"}]}}';
}
function testGenerateModelFromString() {
@@ -69,6 +33,9 @@
$this->fail($e->getMessage());
}
+ #echo "<pre>";
+ #print_r($model);
+
GLOBAL $short_datatype;
$model2 = new MemModel('http://example.com/');
@@ -96,6 +63,10 @@
$statement6 = new Statement(new Resource('http://example.org/about'),
new Resource("http://purl.org/dc/elements/1.1/title2"),
new Literal('Anns HP', 'en', $short_datatype['INTEGER']));
+
+ $statement7= new Statement(new BlankNode('person'),
+ new Resource("http://example.com/testProp1"),
+ new Literal("\"double quote\nnewline\ttab\rcarriage return\\reverse solidus"));
$model2->add($statement1);
@@ -103,6 +74,7 @@
$model2->add($statement3);
$model2->add($statement4);
$model2->add($statement5);
+ $model2->add($statement7);
$this->assertTrue($model->containsAll($model2));
Modified: trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php
===================================================================
--- trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php 2007-12-05 08:18:50 UTC (rev 554)
+++ trunk/rdfapi-php/test/unit/Syntax/jsonSerializer_test.php 2007-12-11 20:27:34 UTC (rev 555)
@@ -26,14 +26,18 @@
$literal1 = new Literal('test literal');
$literal2 = new Literal('test literal', 'en');
- $literal3 = new Literal('test literal', 'de', 'http://www.w3.org/2001/XMLSchema#string');
+ $literal3 = new Literal('test literal', null, 'http://www.w3.org/2001/XMLSchema#string');
+ // test literals with tabs and newlines and double quotes
+ $literal4 = new Literal("test literal\ttab\nnewline\"double quote\rcarriage return\fformfeed\bbackspace\\reverse solidus", null, 'http://www.w3.org/2001/XMLSchema#string');
+
$stm1 = new Statement($res1, $res2, $res3);
$stm2 = new Statement($res1, $res2, $bn1);
$stm3 = new Statement($res1, $res2, $literal1);
$stm4 = new Statement($res1, $res2, $literal2);
$stm5 = new Statement($res1, $res2, $literal3);
$stm6 = new Statement($bn1, $res2, $bn2);
+ $stm7 = new Statement($res2, $res1, $literal4);
$this->model->add($stm1);
$this->model->add($stm2);
@@ -41,6 +45,7 @@
$this->model->add($stm4);
$this->model->add($stm5);
$this->model->add($stm6);
+ $this->model->add($stm7);
}
function testSerialize() {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ca...@us...> - 2008-02-29 15:03:47
|
Revision: 557
http://rdfapi-php.svn.sourceforge.net/rdfapi-php/?rev=557&view=rev
Author: cax
Date: 2008-02-29 07:03:46 -0800 (Fri, 29 Feb 2008)
Log Message:
-----------
initial version
Added Paths:
-----------
trunk/rdfapi-php/rap-pubby/
trunk/rdfapi-php/rap-pubby/.htaccess
trunk/rdfapi-php/rap-pubby/RAPpubbyDataset.php
trunk/rdfapi-php/rap-pubby/RAPpubbyHTMLSer.php
trunk/rdfapi-php/rap-pubby/RAPpubbyResDescr.php
trunk/rdfapi-php/rap-pubby/RAPpubbyURIrewriter.php
trunk/rdfapi-php/rap-pubby/config.php
trunk/rdfapi-php/rap-pubby/doc/
trunk/rdfapi-php/rap-pubby/doc/RAP_Pubby.htm
trunk/rdfapi-php/rap-pubby/doc/phpdoc.css
trunk/rdfapi-php/rap-pubby/example/
trunk/rdfapi-php/rap-pubby/example/group.rdf
trunk/rdfapi-php/rap-pubby/metadata.n3
trunk/rdfapi-php/rap-pubby/prefixes.n3
trunk/rdfapi-php/rap-pubby/rap_pubby.php
trunk/rdfapi-php/rap-pubby/templ/
trunk/rdfapi-php/rap-pubby/templ/404_notFound.html
trunk/rdfapi-php/rap-pubby/templ/rdf-icon.gif
trunk/rdfapi-php/rap-pubby/templ/script.js
trunk/rdfapi-php/rap-pubby/templ/style.css
trunk/rdfapi-php/rap-pubby/templ/template.html
Added: trunk/rdfapi-php/rap-pubby/.htaccess
===================================================================
--- trunk/rdfapi-php/rap-pubby/.htaccess (rev 0)
+++ trunk/rdfapi-php/rap-pubby/.htaccess 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,3 @@
+RewriteEngine on
+RewriteBase /rdfapi-php/rap-pubby/
+RewriteRule ^[^\.]*$ rap_pubby.php
Added: trunk/rdfapi-php/rap-pubby/RAPpubbyDataset.php
===================================================================
--- trunk/rdfapi-php/rap-pubby/RAPpubbyDataset.php (rev 0)
+++ trunk/rdfapi-php/rap-pubby/RAPpubbyDataset.php 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,143 @@
+<?PHP
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby - A Linked Data Frontend for RAP
+// ----------------------------------------------------------------------------------
+
+/**
+ * Installation information is found in the RAP_Pubby documentation.
+ *
+ * @author Radoslaw Oldakowski <ra...@gm...>
+ * @version 1.0, 19.12.2007
+ * @package rap-pubby
+ */
+
+
+// toDo: delete this
+include_once('RAPpubbyURIrewriter.php');
+
+Class RAPpubbyDataset extends Object {
+
+ var $m;
+ var $ns = array();
+ var $metadata;
+
+
+ function RAPpubbyDataset() {
+
+ global $_PUBBY_DATASET;
+
+ $this->loadModel($_PUBBY_DATASET['loadRDF']);
+ $this->loadNamespaces($_PUBBY_DATASET['usePrefixesFrom']);
+ $this->loadMetadata($_PUBBY_DATASET['rdfDocumentMetadata']);
+
+ }
+
+
+ /**
+ *
+ */
+ function & getResDescr ($resURI, $attach_metadata = false) {
+
+ global $_PUBBY_DATASET;
+
+ $r = new Resource(RAPpubbyURIrewriter::pubbyURItoDatasetURI($resURI));
+ $rd_m = new MemModel();
+
+ $rd_m = $this->m->find($r, NULL, NULL);
+ $backlinks = $this->m->find(NULL, NULL, $r);
+ $rd_m->addModel($backlinks);
+
+ $rew_rd_m = & RAPpubbyURIrewriter::rewriteURIsInResDescrModel($rd_m);
+
+ if (!$rew_rd_m->isEmpty() && $_PUBBY_DATASET['addSameAsStatements']) {
+
+ $rew_rd_m->add(new Statement(new Resource($resURI), new Resource(OWL_NS. "sameAs"), $r));
+ }
+ $rew_rd_m->addParsedNamespaces($this->ns);
+
+ $rd = new RAPpubbyResDescr($resURI, $rew_rd_m);
+
+ if ($attach_metadata && !$rd->isEmpty()) {
+ $rd->attachMetadata($this->getMetadata($resURI));
+ }
+ return $rd;
+ }
+
+
+ // private -----------------------------------------------------
+
+
+ /**
+ * @return RAP model with metadata, blank node replaced with resource URI
+ */
+ function & getMetadata ($resURI) {
+
+ $dataURI = RAPpubbyURIrewriter::resURItoDataURI($resURI);
+
+ $metaData = $this->metadata;
+ $metaData->replace(new BlankNode(BNODE_PREFIX .'1'), NULL, NULL, new Resource($dataURI));
+
+ return $metaData;
+ }
+
+
+ /**
+ *
+ */
+ function loadModel($url) {
+
+ // load model from file
+ if ($url) {
+ $this->m = new MemModel();
+ $this->m->load($url);
+ }
+ else {
+ $db = new DbStore(PUBBY_DB_DRIVER, PUBBY_DB_HOST, PUBBY_DB_DB, PUBBY_DB_USER, PUBBY_DB_PASS);
+ $this->m = $db->getModel(PUBBY_DBMODEL);
+ }
+ }
+
+
+ /**
+ * loads namespaces from file or rewrites from configuration model
+ */
+ function loadNamespaces($url) {
+
+ if ($url) {
+
+ $nmsp_m = new MemModel();
+ $nmsp_m->load($url);
+ $this->ns = $nmsp_m->getParsedNamespaces();
+ if (!$this->ns) {
+ trigger_error("The file:" .$url ."does not contain any namespace declarations."
+ ."The prefixes from the configuration model will be used instead");
+ }
+ }
+ else {
+
+ $nmsp = $this->m->getParsedNamespaces();
+ if ($nmsp) {
+ $this->ns = RAPpubbyURIrewriter::rewrNamespaces($nmsp);
+ }
+ }
+ }
+
+
+ /**
+ *
+ */
+ function loadMetadata($url) {
+
+ if ($url) {
+ $this->metadata = new MemModel();
+ $this->metadata->load($url);
+ }
+ }
+
+
+
+
+}
+
+?>
\ No newline at end of file
Added: trunk/rdfapi-php/rap-pubby/RAPpubbyHTMLSer.php
===================================================================
--- trunk/rdfapi-php/rap-pubby/RAPpubbyHTMLSer.php (rev 0)
+++ trunk/rdfapi-php/rap-pubby/RAPpubbyHTMLSer.php 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,361 @@
+<?PHP
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby - A Linked Data Frontend for RAP
+// ----------------------------------------------------------------------------------
+
+/**
+ * Installation information is found in the RAP_Pubby documentation.
+ *
+ * @author Radoslaw Oldakowski <ra...@gm...>
+ * @version 1.0, 19.12.2007
+ * @package rap-pubby
+ */
+
+
+include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+
+
+Class RAPpubbyHTMLSer extends Object {
+
+ var $htmlTemplate;
+ var $htmlTemplate_404;
+ var $placeholders = array(
+ '##_templInclDirURL_##' => '',
+ '##_projetName_##' => '',
+ '##_projectHomepage_##' => '',
+ '##_resURI_##' => '',
+ '##_repURIdata_##' => '',
+ '##_resourceLabel_##' => '',
+ '##_shortDescription_##' => '',
+ '##_imgLink_##' => '',
+ '##_prop_tableRows_##' => '',
+ );
+
+
+ /**
+ *
+ */
+ function RAPpubbyHTMLSer ($template = PUBBY_HTML_SER__TEMPLATE, $template_404 = PUBBY_HTML_SER__TEMPLATE_404) {
+
+ $this->loadTemplates($template, $template_404);
+
+ $this->placeholders['##_templInclDirURL_##'] = PUBBY_WEBBASE .PUBBY_HTML_SER__TEMPL_INCL_DIR;
+ $this->placeholders['##_projectName_##'] = PUBBY_HTML_SER__PROJECT_NAME;
+ $this->placeholders['##_projectHomepage_##'] = PUBBY_HTML_SER__PROJECT_HOMEPAGE;
+
+ }
+
+
+ /**
+ *
+ */
+ function serialize (&$rd) {
+
+
+ if ($rd->isEmpty()) {
+ $html = $this->htmlTemplate_404;
+ }
+ else {
+ $html = $this->htmlTemplate;
+ }
+ $ph = $this->generatePlaceholderValues($rd);
+ $html = str_ireplace(array_keys($ph), $ph, $html);
+
+ return $html;
+ }
+
+
+ /**
+ *
+ */
+ function loadTemplates($t, $t_404) {
+
+ if (file_exists($t)) {
+ $file = fopen($t, "r");
+ if ($file) {
+ $this->htmlTemplate = fread($file,filesize($t));
+ fclose($file);
+ }
+ }
+ else {
+ trigger_error("Could not find template file: $t, ");
+ $this->htmlTemplate = $this->getBasicTemplate();
+ }
+
+ if (file_exists($t_404)) {
+ $file = fopen($t_404, "r");
+ if ($file) {
+ $this->htmlTemplate_404 = fread($file,filesize($t_404));
+ fclose($file);
+ }
+ }
+ else {
+ trigger_error("Could not find template file: $t_404, ");
+ $this->htmlTemplate_404 = $this->getBasicTemplate_404();
+ }
+
+ }
+
+
+ /**
+ *
+ */
+ function getBasicTemplate() {
+
+ return '<h1>##_resURI_##</h1>
+ <table>
+ <tr><td><h3>Property</h3></td> <td><h3>Value</h3></td></tr>
+ ##_prop_tableRows_##
+ </table>';
+ }
+
+ function getBasicTemplate_404() {
+
+ return '<h1>##_resURI_##</h1>
+ <p>The requested resource does not exist at this server, or no information about it is available.</p>';
+ }
+
+
+ /**
+ *
+ */
+ function generatePlaceholderValues (&$rd) {
+
+ $res = & $rd->getResource();
+ $m = & $rd->getModel();
+
+ $ph = $this->placeholders;
+ $ph['##_resURI_##'] = $res->getURI();
+ $ph['##_repURIdata_##'] = $rd->getDataURI();
+ $ph['##_resourceLabel_##'] = $this->findLabel($m, $res);
+ $ph['##_shortDescription_##'] = $this->findComment($m, $res);
+ $ph['##_imgLink_##'] = $this->findImgLink($m, $res);
+ $ph['##_prop_tableRows_##'] = $this->renderResourceProperties($m, $res);
+
+ return $ph;
+ }
+
+
+ /**
+ * find only the first occurance of the label
+ */
+ function findLabel(&$m, &$res) {
+
+ global $_PUBBY_HTML_SER;
+ return $this->findLiteralValueLang($m, $res, $_PUBBY_HTML_SER['labelProperty']);
+ }
+
+
+ /**
+ * find only the first occurance of the comment
+ */
+ function findComment(&$m, &$res) {
+
+ global $_PUBBY_HTML_SER;
+ return $this->findLiteralValueLang($m, $res, $_PUBBY_HTML_SER['commentProperty']);
+ }
+
+
+ /**
+ *
+ */
+ function findImgLink (&$m, &$res) {
+
+ global $_PUBBY_HTML_SER;
+
+ foreach ($_PUBBY_HTML_SER['imageProperty'] as $prop) {
+
+ $triple = $m->findFirstMatchingStatement($res, $prop, NULL);
+ if ($triple) {
+ return $triple->getObject()->getURI();
+ }
+ }
+ return '';
+ }
+
+
+ /**
+ * find only the first occurance of the Literal from an array of properties
+ */
+ function findLiteralValueLang(&$m, &$res, &$prop_array) {
+
+ $tmp = '';
+
+ // if no default lang is specified find any literal value
+ if (PUBBY_HTML_SER__DEFAULT_LANG == '') {
+
+ foreach ($prop_array as $prop) {
+
+ $triple = $m->findFirstMatchingStatement($res, $prop, NULL);
+ if ($triple) {
+ return $triple->getObject()->getLabel();
+ }
+ }
+ }
+ else {
+ foreach ($prop_array as $prop) {
+
+ $result = $m->find($res, $prop, NULL);
+
+ $iter = $result->getStatementIterator();
+ while ($iter->hasNext()) {
+
+ $triple = $iter->next();
+ if ($triple->getObject()->getLanguage() == PUBBY_HTML_SER__DEFAULT_LANG) {
+ return $triple->getObject()->getLabel();
+ }
+ }
+ // if no label with default lang was found take the first one
+ // and store it in $tmp because another property could contain the default lang
+ if (!$result->isEmpty()) {
+ $triple = $result->findFirstMatchingStatement($res, $prop, NULL);
+ if ($triple) {
+ $tmp = $triple->getObject()->getLabel();
+ }
+ }
+ }
+ }
+ return $tmp;
+ }
+
+
+ /**
+ *
+ */
+ function renderResourceProperties (&$m, &$res) {
+
+ $prop = array();
+
+ // find properties
+ $result = $m->find($res, NULL, NULL);
+
+ $iter = $result->getStatementIterator();
+ while ($iter->hasNext()) {
+ $triple = $iter->next();
+ $propURI = $triple->getPredicate()->getURI();
+ $prop[$propURI][false][] = $triple->getObject();
+ }
+
+ // find inverse properteis (backlinks)
+ $result = $m->find(NULL, NULL, $res);
+
+ $iter = $result->getStatementIterator();
+ while ($iter->hasNext()) {
+ $triple = $iter->next();
+ $propURI = $triple->getPredicate()->getURI();
+ // inverse the property --> get subject instead of object
+ $prop[$propURI][true][] = $triple->getSubject();
+
+ }
+
+ // sort properties
+ uksort($prop, array($this, '_sortURIbyQName'));
+
+ // render table rows with resource properties
+ $nsPrefix = $m->getParsedNamespaces(); if (!$nsPrefix) $nsPrefix = array();
+ $html_tableRows = '';
+ $tr_class = array(true => 'odd', false => 'even');
+ $odd = true;
+
+ foreach ($prop as $propURI => $propType) {
+ foreach ($propType as $inverseProp => $valArray) {
+
+ $tr='
+ <tr class="' .$tr_class[$odd] .'">
+ <td class="property">'
+ .$this->renderPropURI($propURI, $nsPrefix, $inverseProp)
+ .'</td>
+ <td>
+ <ul>';
+ foreach ($valArray as $propValue) {
+
+ if (is_a($propValue, "Literal")) {
+ $tr .='
+ <li>'
+ .$this->renderLiteral($propValue)
+ .'</li>';
+ }
+ else {
+ $tr .='
+ <li>'
+ .$this->renderURI($propValue->getURI(), $nsPrefix)
+ .'</li>';
+ }
+ }
+ $tr .='
+ </ul>
+ </td>
+ </tr>';
+ $odd = !$odd;
+ $html_tableRows .= $tr;
+ }
+ }
+
+ return $html_tableRows;
+ }
+
+
+ /**
+ *
+ */
+ function renderLiteral ($literal) {
+
+ $html = '<span class="literal">' .$literal->getLabel();
+ if ($literal->getLanguage()) {
+ $html .= '<small> (' .$literal->getLanguage() .')</small>';
+ }
+ return $html .= '</span>';
+
+ }
+
+
+ /**
+ *
+ */
+ function renderPropURI ($URI, &$nsPrefix, $inverseProp=false) {
+
+ if ($inverseProp) {
+ return '<small>is </small>' .$this->renderURI($URI, $nsPrefix) .'<small> of</small>';
+ }
+ else {
+ return $this->renderURI($URI, $nsPrefix);
+ }
+
+ }
+
+
+ /**
+ *
+ */
+ function renderURI($URI, &$nsPrefix) {
+
+ $ns = RDFUtil::guessNamespace($URI);
+ $qName = RDFUtil::guessName($URI);
+
+ $html = '<a class="uri" href="' .$URI .'" title="' .$URI .'">';
+
+ if (array_key_exists($ns, $nsPrefix)) {
+ $html .= '<small>' .$nsPrefix[$ns] .':</small>' .$qName;
+ }
+ else {
+ $html .= $URI;
+ }
+ $html .= '</a>';
+
+ return $html;
+
+ }
+
+
+ /**
+ * Call-back function for uksort()
+ */
+ function _sortURIbyQName ($a, $b) {
+
+ return strcasecmp(RDFUtil::guessName($a), RDFUtil::guessName($b));
+ }
+
+}
+
+?>
\ No newline at end of file
Added: trunk/rdfapi-php/rap-pubby/RAPpubbyResDescr.php
===================================================================
--- trunk/rdfapi-php/rap-pubby/RAPpubbyResDescr.php (rev 0)
+++ trunk/rdfapi-php/rap-pubby/RAPpubbyResDescr.php 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,127 @@
+<?PHP
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby - A Linked Data Frontend for RAP
+// ----------------------------------------------------------------------------------
+
+/**
+ * Installation information is found in the RAP_Pubby documentation.
+ *
+ * @author Radoslaw Oldakowski <ra...@gm...>
+ * @version 1.0, 19.12.2007
+ * @package rap-pubby
+ */
+
+
+Class RAPpubbyResDescr extends Object {
+
+ var $res;
+ var $m_rd;
+ var $m_metadata;
+
+
+ /**
+ *
+ */
+ function RAPpubbyResDescr ($resURI, &$m) {
+
+ $this->res = new Resource($resURI);
+ $this->m_rd = &$m;
+ $this->m_metadata = new MemModel();
+ }
+
+
+ /**
+ *
+ */
+ function isEmpty() {
+
+ return $this->m_rd->isEmpty();
+ }
+
+
+ /**
+ *
+ */
+ function & getResource() {
+
+ return $this->res;
+ }
+
+
+ /**
+ *
+ */
+ function getResURI() {
+
+ return $this->res->getURI();
+ }
+
+
+ /**
+ *
+ */
+ function getDataURI() {
+
+ return RAPpubbyURIrewriter::resURItoDataURI($this->res->getURI());
+ }
+
+
+ /**
+ *
+ */
+ function getPageURI() {
+
+ return RAPpubbyURIrewriter::resURItoPageURI($this->res->getURI());
+ }
+
+
+ /**
+ *
+ */
+ function & getModel() {
+
+ return $this->m_rd;
+ }
+
+
+ /**
+ *
+ */
+ function attachMetadata(&$m) {
+
+ $this->m_rd->addModel($m);
+ $this->m_metadata = &$m;
+ }
+
+
+ /**
+ *
+ */
+ function & getMetadataModel() {
+
+ return $this->m_metadata;
+ }
+
+
+ function serialize ($format) {
+
+ switch ($format) {
+ case "html":
+ $s = new RAPpubbyHTMLSer();
+ return $s->serialize($this);
+ case "n3":
+ include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+ $s = new N3Serializer();
+ return $s->serialize($this->m_rd);
+ case "rdf/xml":
+ default:
+ include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+ $s = new RdfSerializer();
+ return $s->serialize($this->m_rd);
+ }
+ }
+
+}
+
+?>
\ No newline at end of file
Added: trunk/rdfapi-php/rap-pubby/RAPpubbyURIrewriter.php
===================================================================
--- trunk/rdfapi-php/rap-pubby/RAPpubbyURIrewriter.php (rev 0)
+++ trunk/rdfapi-php/rap-pubby/RAPpubbyURIrewriter.php 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,181 @@
+<?PHP
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby - A Linked Data Frontend for RAP
+// ----------------------------------------------------------------------------------
+
+/**
+ * Installation information is found in the RAP_Pubby documentation.
+ *
+ * @author Radoslaw Oldakowski <ra...@gm...>
+ * @version 1.0, 19.12.2007
+ * @package rap-pubby
+ */
+
+
+Class RAPpubbyURIrewriter extends Object {
+
+
+ /**
+ *
+ */
+ function datasetURItoPubbyURI($uri) {
+
+ global $_PUBBY_DATASET;
+
+ return str_ireplace($_PUBBY_DATASET['datasetBase'], PUBBY_WEBBASE .$_PUBBY_DATASET['webResourcePrefix'], $uri);
+ }
+
+
+ /**
+ *
+ */
+ function pubbyURItoDatasetURI($uri) {
+
+ global $_PUBBY_DATASET;
+
+ return str_ireplace(PUBBY_WEBBASE .$_PUBBY_DATASET['webResourcePrefix'], $_PUBBY_DATASET['datasetBase'], $uri);
+ }
+
+
+ /**
+ *
+ */
+ function resURItoDataURI($resURI, $output='') {
+
+ $dataURI = PUBBY_WEBBASE ."data/" .substr($resURI, strlen(PUBBY_WEBBASE));
+
+ if ($output) {
+ return $dataURI ."?output=$output";
+ }
+ return $dataURI;
+ }
+
+
+ /**
+ *
+ */
+ function resURItoPageURI($resURI) {
+
+ return PUBBY_WEBBASE ."page/" .substr($resURI, strlen(PUBBY_WEBBASE));
+ }
+
+
+ /**
+ *
+ */
+ function dataURItoResURI($dataURI, $outputParam='') {
+
+ $resURI = PUBBY_WEBBASE .substr($dataURI, strlen(PUBBY_WEBBASE. 'data/'));
+
+ if ($outputParam) {
+ return substr($resURI, 0, stripos($resURI, "?$outputParam"));
+ }
+ return $resURI;
+ }
+
+
+ /**
+ *
+ */
+ function pageURItoResURI($pageURI) {
+
+ return PUBBY_WEBBASE .substr($pageURI, strlen(PUBBY_WEBBASE. 'page/'));
+ }
+
+
+ /**
+ *
+ */
+ function rewrNamespaces($ns) {
+
+ global $_PUBBY_DATASET;
+
+ foreach ($ns as $n => $prefix) {
+ if (stripos($n, $_PUBBY_DATASET['datasetBase']) !== false) {
+ unset($ns[$n]);
+ $ns[RAPpubbyURIrewriter::datasetURItoPubbyURI($n)] = $prefix;
+ }
+ }
+ asort($ns);
+ return $ns;
+ }
+
+
+ /**
+ *
+ */
+ function & rewriteURIsInResDescrModel(&$rd_m) {
+
+ global $_PUBBY_DATASET;
+ global $namespaces;
+
+ $rew_rd_m = new MemModel();
+
+ // uri rewriting + regex filtering
+ if ($_PUBBY_DATASET['datasetURIPattern'] != '') {
+
+ $l = strlen($_PUBBY_DATASET['datasetBase']);
+
+ $iter = $rd_m->getStatementIterator();
+ while ($iter->hasNext()) {
+
+ $triple = $iter->next();
+ $subj = $triple->getSubject();
+
+ // if subjURI is a datasetURI & does not match the pattern
+ if (stripos($subj->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 &&
+ !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($subj->getURI(), $l))) {
+ continue;
+ }
+ else {
+ // if predURI is a datasetURI & does not match the pattern
+ $pred = $triple->getPredicate();
+ if (stripos($pred->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 &&
+ !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($pred->getURI(), $l))) {
+ continue;
+ }
+ else {
+ // if obj is a Literal & objeURI is a datasetURI & does not match the pattern
+ $obj = $triple->getObject();
+ if (!is_a($obj, "Literal")) {
+ if (stripos($obj->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 &&
+ !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($obj->getURI(), $l))) {
+ continue;
+ }
+ else {
+ $obj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($obj->getURI()));
+ }
+ }
+ $subj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($subj->getURI()));
+ $pred = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($pred->getURI()));
+
+ $rew_rd_m->add(new Statement($subj, $pred, $obj));
+ }
+ }
+ }
+ }
+ else {
+
+ $iter = $rd_m->getStatementIterator();
+ while ($iter->hasNext()) {
+
+ $triple = $iter->next();
+
+ $subj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($triple->getSubject()->getURI()));
+ $pred = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($triple->getPredicate()->getURI()));
+ $obj = $triple->getObject();
+
+ if (!is_a($obj, "Literal")) {
+ $obj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($obj->getURI()));
+ }
+ $rew_rd_m->add(new Statement($subj, $pred, $obj));
+ }
+ }
+
+ return $rew_rd_m;
+ }
+
+}
+
+?>
\ No newline at end of file
Added: trunk/rdfapi-php/rap-pubby/config.php
===================================================================
--- trunk/rdfapi-php/rap-pubby/config.php (rev 0)
+++ trunk/rdfapi-php/rap-pubby/config.php 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,146 @@
+<?PHP
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby - A Linked Data Frontend for RAP
+// ----------------------------------------------------------------------------------
+
+/**
+ * Installation information is found in the RAP_Pubby documentation.
+ *
+ * @author Radoslaw Oldakowski <ra...@gm...>
+ * @version 1.0, 29.02.2008
+ * @package rap-pubby
+ */
+
+// ----------------------------------------------------------------------------------
+// Include RAP Classes
+// ----------------------------------------------------------------------------------
+
+// Defines RAP include directories
+// NOTE: Modify this if your rap-pubby is not installed in RAP subdirectory
+define("RDFAPI_INCLUDE_DIR", "../api/");
+include(RDFAPI_INCLUDE_DIR . "RdfAPI.php");
+
+
+// include RAPpubby classes
+include_once('RAPpubbyURIrewriter.php');
+include_once('RAPpubbyDataSet.php');
+include_once('RAPpubbyResDescr.php');
+include_once('RAPpubbyHTMLSer.php');
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby Server Configuration Section
+// ----------------------------------------------------------------------------------
+
+
+// The root URL where the RAP_Pubby web application is installed, e.g. http://myserver/mydataset/.
+define('PUBBY_WEBBASE', 'http://localhost/rdfapi-php/rap-pubby/');
+
+// The URI of a resource which description will be displayed as the home page of the RAP_Pubby installation.
+// Note that you have to specify a dataset URI, not a mapped web URI.
+define('PUBBY_INDEX_RESOURCE', 'http://www4.wiwiss.fu-berlin.de/is-group/projects/RAP');
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby Database Configuration
+// ----------------------------------------------------------------------------------
+
+// Note: in order to serve a DbModel the $_PUBBY_DATASET['loadRDF'] parameter must be set to '';
+define('PUBBY_DB_DRIVER', '');
+define('PUBBY_DB_HOST', '');
+define('PUBBY_DB_DB', '');
+define('PUBBY_DB_USER', '');
+define('PUBBY_DB_PASS', '');
+
+define('PUBBY_DBMODEL', '');
+
+
+// ----------------------------------------------------------------------------------
+// RAP_Pubby Dataset Configuration Section
+// ----------------------------------------------------------------------------------
+
+$_PUBBY_DATASET = array(
+
+ // Load an RDF document from the Web or the file system and use it as the data source.
+ // If specified, the database connection configured above will be ignored.
+ 'loadRDF' => 'example/group.rdf',
+
+ // The common URI prefix of the resource identifiers in the served dataset.
+ // Note: Only resources with this prefix will be mapped and made available by RAP_Pubby
+ 'datasetBase' => 'http://www4.wiwiss.fu-berlin.de/is-group/',
+
+ // If present, only dateset URIs matching this regular expression will be mapped and made available by RAP_Pubby.
+ // The regular expression must match everything after the $_PUBBY_DATASET['datasetBase'] part of the URI.
+ // For example: datasetBase = 'http://example.org/' and datasetURIPattern = '/(users|documents)\/.*/'
+ // This will publish the dataset URI http://example.org/users/alice,
+ // but not http://example.org/invoices/5395842 because the URI part invoices/5395842 does not match the regular expression.
+ // default value = '';
+ 'datasetURIPattern' => '',
+
+ // If present, this string will be prefixed to the mapped web URIs. This is useful if you have to avoid potential name clashes
+ // with URIs already used by the server itself. For example, if the dataset includes a URI http://mydataset/page,
+ // and the dataset prefix is http://mydataset/, then there would be a clash after mapping because RAP_Pubby reserves
+ // the mapped URI http://myserver/mydataset/page for its own use. In this case, you may specify a prefix like "resource/",
+ // which will result in a mapped URI of http://myserver/mydataset/resource/page.
+ // NOTE: the prefix must end with "/"
+ 'webResourcePrefix' => '',
+
+ // Links to an RDF document whose prefix declarations will be used in output.
+ // e.g. 'usePrefixesFrom' => 'prefixes.n3', You can use the file prefixes.n3 in rap-pubby directory as template.
+ // Defaults to the empty URL, which means the prefixes from the input RAP model will be used.
+ 'usePrefixesFrom' => 'prefixes.n3',
+
+ // All statements inside the metadata file will be added as metadata to the RDF documents published
+ // for this dataset. This feature can be used for instance to add licensing information to your published documents.
+ // You can use the file metadata.n3 in rap-pubby directory as template.
+ 'rdfDocumentMetadata' => 'metadata.n3',
+
+
+ // If set to true, an owl:sameAs statement of the form <web_uri> owl:sameAs <dataset_uri> will be present in Linked Data output.
+ 'addSameAsStatements' => false,
+);
+
+
+// ----------------------------------------------------------------------------------
+// Pubby HTML Output Setting
+// ----------------------------------------------------------------------------------
+
+// URL of the template file used in HTML output
+define ('PUBBY_HTML_SER__TEMPLATE', 'templ/template.html');
+
+// URL of the template file rendering '404 - Not Found' information used in HTML output
+define ('PUBBY_HTML_SER__TEMPLATE_404', 'templ/404_notFound.html');
+
+// Link to directory where template includes (css-files, scripts, images) are located
+define ('PUBBY_HTML_SER__TEMPL_INCL_DIR' , 'templ/');
+
+// The name of the project, for display in page titles
+define ('PUBBY_HTML_SER__PROJECT_NAME', 'PubbyExample@Localhost');
+
+// A project homepage or similar URL, for linking in page titles
+define ('PUBBY_HTML_SER__PROJECT_HOMEPAGE', 'http://localhost/rap-pubby/doc/RAP_Pubby.htm');
+
+// For resource label and short description
+define ('PUBBY_HTML_SER__DEFAULT_LANG', 'en');
+
+// The value of these RDF properties, if present in the dataset, will be used as labels and page titles for resources.
+// Note: If multiple properties are present only the first one found (in default language, if specified) will be showed.
+$_PUBBY_HTML_SER['labelProperty'] = array (
+ new Resource(RDF_SCHEMA_URI ."label"),
+ new Resource(DC_NS ."title"),
+ new Resource(FOAF_NS ."name"),
+);
+
+// The value of these RDF properties, if present in the dataset, will be used as short textual description for resources.
+// Note: If multiple properties are present only the first one found (in default language, if specified) will be showed.
+$_PUBBY_HTML_SER['commentProperty'] = array (
+ new Resource(RDF_SCHEMA_URI ."comment"),
+ new Resource(DC_NS ."description"),
+);
+
+// The value of these RDF properties, if present in the dataset, will be used as an image URL to show a depiction of the item.
+// Note: If multiple properties are present only the first one found will be showed.
+$_PUBBY_HTML_SER['imageProperty'] = array (
+ new Resource(FOAF_NS ."depiction"),
+);
+
+?>
\ No newline at end of file
Added: trunk/rdfapi-php/rap-pubby/doc/RAP_Pubby.htm
===================================================================
--- trunk/rdfapi-php/rap-pubby/doc/RAP_Pubby.htm (rev 0)
+++ trunk/rdfapi-php/rap-pubby/doc/RAP_Pubby.htm 2008-02-29 15:03:46 UTC (rev 557)
@@ -0,0 +1,290 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html><head><title>RDF Net API</title>
+
+<meta content="text/html; charset=windows-1252" http-equiv="Content-Type">
+<link href="phpdoc.css" rel="stylesheet" type="text/css">
+</head>
+<body bgcolor="#ffffff">
+
+<h3>RDF API for PHP </h3>
+<h1>RAP_Pubby -
+
+
+ A Linked Data Frontend for RAP </h1>
+<p>This document is part of the <a href="http://sites.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/tests.html">RAP - Rdf API for PHP</a> documentation.</p>
+<p>Radoslaw Oldakowski <<a href="mailto:ra...@gm...">ra...@gm...</a>><br>
+Jan 2008</p>
+<br>
+
+<h2>About</h2>
+<p><strong>RAP_Pubby</strong> can be used to add <strong>Linked Data interfaces</strong> to RAP models.</p>
+<p> <a href="http://linkeddata.org/">Linked Data </a> is a style of publishing data on the Semantic Web that makes it easy to interlink, discover and consume data on the Semantic Web. It allows a wide variety of existing RDF browsers (e.g. <a href="http://sites.wiwiss.fu-berlin.de/suhl/bizer/ng4j/disco/">Disco </a>, <a href="http://www.w3.org/2005/ajar/tab">Tabulator </a>, <a href="http://demo.openlinksw.com/DAV/JS/rdfbrowser/index.html">OpenLink Browser </a>), RDF crawlers (e.g. <a href="http://www.swse.org/">SWSE </a>, <a href="http://swoogle.umbc.edu/">Swoogle </a>), and query agents (e.g. <a href="http://sites.wiwiss.fu-berlin.de/suhl/bizer/ng4j/semwebclient/">SemWeb Client Library </a>, <a href="http://moustaki.org/swic/">SWIC </a>) to access t...
[truncated message content] |