Linked Data

Structured Data on the Web

by David Wood, Marsha Zaidman, and Luke Ruth

Welcome! Here you will find all of the sample applications and code listings for the book Linked Data. This will also serve as an ongoing forum for questions and comments regarding the book.

Where to Buy

Manning

eBook and print

Amazon

Print only

Barnes & Noble

Print only

Authors' site

Heads up! Chapter 1 and chapter 3 are available for free via Manning.com.


Applications & Services

EPA

An application from chapter 1 that demonstrates a real-world application of Linked Data and how easily different datasets can be brought together.

FOAF Generator

An application from chapter 4 that gives users the ability to create their own Linked Data FOAF profile in a simple Web form.

Notes

An application from chapter 9 that lays out a slightly more advanced example of creating and editing RDF classes via a Note tracker.

Weather

An application from chapter 9 that brings together disparate data sources in a live Web app using stock JavaScript and CSS to extend functionality.

Bonobos

A Callimachus application from chapter 9 that lays out a basic example of creating web pages using RDF classes and a small bit of Linked Data.


Code Listings

Listing 1.1 - Example schema for the figure 1.4 spreadsheet in Turtle format

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix dc: <http://purl.org/dc/terms/> .
@prefix loc: <http://www.daml.org/2001/10/html/airport-ont#> .
@prefix eg: <http://example.com/> .
@prefix qb: <http://purl.org/linked-data/cube#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix sdmxa: <http://purl.org/linked-data/sdmx/2009/attribute#> .
@prefix sdmx-measure: <http://purl.org/linked-data/sdmx/2009/measure#> .

<http://example.com/my_temperature_data>
  rdfs:label “Temperature observations”;
  rdfs:comment “Temperature observations at Galway Airport”;
  loc:location <http://dbpedia.org/resource/Galway_Airport>;
  dc:creator “Michael Hausenblas”.

eg:day a rdf:Property, qb:MeasureProperty;
  rdfs:label “day”@en;
  rdfs:subPropertyOf sdmx-measure:obsValue;
  sdmxa:unitMeasure <http://dbpedia.org/resource/Day> ;
  rdfs:range xsd:date .

eg:temperature a rdf:Property, qb:MeasureProperty;
  rdfs:label “temperature”@en;
  rdfs:subPropertyOf sdmx-measure:obsValue;
  sdmxa:unitMeasure <http://dbpedia.org/resource/Celsius> ;
  rdfs:range xsd:decimal .
                                            

Listing 1.2 - Excerpt of the Linked Data about bonobos in Turtle format

@prefix dbpedia:    <http://dbpedia.org/resource/> .
@prefix dbpedia-owl:    <http://dbpedia.org/ontology/> . 
@prefix foaf:    <http://xmlns.com/foaf/0.1/> .

dbpedia:Bonobo    rdf:type    dbpedia-owl:Eukaryote ,
        dbpedia-owl:Mammal , 
        dbpedia-owl:Animal .

dbpedia:Bonobo    foaf:name    "Bonobo"@en ,
        foaf:depiction <http://upload.wikimedia.org/wikipedia/commons/a/a6/Bonobo-04.jpg> ;
                                            

Listing 1.3 - HTML for Linked Data elements shown in figure 1.10

Linked Data

Listing 1.4 - JavaScript click function handlers for the HTML elements shown in listing 1.3

jQuery(function($) {
    $('#rdfxml').click(function(event) {
        event.preventDefault();
        var request = $.ajax({
            url: '?describe',
            headers: { Accept : "application/rdf+xml" }
        });
                        
        request.done(function() { 
            var win = window.open('', document.URL);
            win.document.write('<pre>\n' + request.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '\n</pre>');
         });
                
         request.fail(function() { 
             alert("We're sorry, the request could not be completed at this time. Please try again shortly."); 
         });
    });
    
    $("#turtle").click(function(event) {
        event.preventDefault();
        var request = $.ajax({
            url: '?describe',
            headers: { Accept : "text/turtle" }
        });
                        
        request.done(function() { 
            var win = window.open('', document.URL);
            win.document.write('<pre>\n' + request.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '\n</pre>');
        });
                
        request.fail(function() { 
            alert("We're sorry, the request could not be completed at this time. Please try again shortly."); 
        });
    });
});
                                            

Listing 1.5 - Extract from the Browns Ferry nuclear power plant Linked Data

@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix place: <http://purl.org/ontology/places#> .
@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .

<http://usepa.3roundstones.net/facilities/110000589355> place:point_on_map "34.710917,-87.112"^^place:latlong ;
foaf:depiction <http://upload.wikimedia.org/wikipedia/commons/a/ab/Browns_ferry_NPP.jpg> ;
vcard:adr <http://usepa.3roundstones.net/addresses/shawrdatnuclearplantrdathensal35611usa> .
                                            

Listing 1.6 - Linked Data for the Browns Ferry nuclear power plant street address

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .
@prefix frs: <http://usepa.3roundstones.net/id/us/fed/agency/epa/frs/schema#> .

<http://usepa.3roundstones.net/addresses/shawrdatnuclearplantrdathensal35611usa> a vcard:Address ;
    vcard:street-address "Shaw Rd At Nuclear Plant Rd." ;
    vcard:locality "Athens" ;
    vcard:region "Alabama" ;
    frs:county_name "Limestone" ;
    frs:fips_county_code "01083" ;
    frs:state_code "AL" ;
    frs:state <http://usepa.3roundstones.net/states/AL> ;
    vcard:postal-code "35611" ;
    vcard:country-name "USA" ;
    foaf:based_near <zip:35611> , <zip:35611> .
                                            

Listing 2.1 - A custom RDF vocabulary in Turtle format

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix odor: <http://linkeddatadeveloper.com/ns/odor#> .

# Classes
odor:OldSocks a rdfs:Class, owl:Class ;
rdfs:label "Old socks" ;
  rdfs:comment "The odor associated with old socks or bonobos." .

# Properties
odor:smellsLike
    rdf:type rdf:Property ;
    rdfs:label "smells like" ;
    rdfs:comment "Relates an arbitrary subject to a class that identifies a particular odor." .

                                            

Listing 2.2 - Bonobo example data in Turtle format

@prefix dbpedia:    <http://dbpedia.org/resource/> .
@prefix dbpedia-owl:    <http://dbpedia.org/ontology/> .
@prefix foaf:    <http://xmlns.com/foaf/0.1/> .
@prefix ex: <http://example.com/> .
@prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

dbpedia:Bonobo
    rdf:type    dbpedia-owl:Eukaryote , dbpedia-owl:Mammal ,
dbpedia-owl:Animal ;
    rdfs:comment "The bonobo, Pan paniscus, previously called the pygmy chimpanzee and less often, the dwarf or gracile chimpanzee, is a great ape and one of the two species making up the genus Pan; the other is Pan troglodytes, or the common chimpanzee. Although the name \"chimpanzee\" is sometimes used to refer to both species together, it is usually understood as referring to the common chimpanzee, while Pan paniscus is usually referred to as the bonobo."@en ;
    foaf:depiction    <http://upload.wikimedia.org/wikipedia/commons/a/a6/Bonobo-04.jpg> ;
    foaf:name    "Bonobo"@en ;
    rdfs:seeAlso <http://eol.org/pages/326448/overview>
.

<http://dbpedia.org/resource/San_Diego_Zoo> rdfs:label "San Diego Zoo"@en ;
    <http://semanticweb.org/wiki/Property:Contains> dbpedia:Bonobo ;
    vcard:adr _:1 ;
    dbpedia:Exhibit _:2 ;
    a ex:Zoo
.

<http://dbpedia.org/resource/Columbus_Zoo_and_Aquarium> rdfs:label "Columbus Zoo and Aquarium"@en ;
    <http://semanticweb.org/wiki/Property:Contains> dbpedia:Bonobo ;
    a ex:Zoo
.

_:1 vcard:locality "San Diego" ;
    vcard:region "California" ;
    vcard:country-name "USA"
.

_:2 rdfs:label "Pygmy Chimps at Bonobo Road"@en ;
    <http://dbpedia.org/property/dateStart> "1993-04-03-08:00"^^xsd:date ;
    <http://semanticweb.org/wiki/Property:Contains> dbpedia:Bonobo
.

ex:Zoo a rdfs:Class .
                                            

Listing 2.3 - Bonobo example data in RDF/XML format


                                            

Listing 2.4 - Bonobo example data in HTML+RDFa format


    
        
        
            Stuff we know about bonobos
        
    
    
        

Here are some things we know about Bonobos: The bonobo, Pan paniscus, previously called the pygmy chimpanzee and less often, the dwarf or gracile chimpanzee, is a great ape and one of the two species making up the genus Pan; the other is Pan troglodytes, or the common chimpanzee. Although the name "chimpanzee" is sometimes used to refer to both species together, it is usually understood as referring to the common chimpanzee, while Pan paniscus is usually referred to as the bonobo. Bonobos are mammalian animals and are thus also eukaryotes. More information may be found at the bonobo entry at the Encyclopedia of Life

Some zoos that contain bonobos include:

  • Columbus Zoo and Aquarium
  • San Diego Zoo which is located in San Diego, California, USA.The main bonobo exhibit is called Pygmy Chimps at Bonobo Road. It has been at the San Diego Zoo since Saturday, 03 April 1993.

Listing 2.5 - Bonobo example data in JSON-LD format

{
  "@context": {
    "foaf": "http://xmlns.com/foaf/0.1/",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "vcard": "http://www.w3.org/2006/vcard/ns#",
    "xsd": "http://www.w3.org/2001/XMLSchema#"
  },
  "@graph": [
    {
      "@id": "_:t0",
      "vcard:country-name": "USA",
      "vcard:locality": "San Diego",
      "vcard:region": "California"
    },
    {
      "@id": "_:t1",
      "http://dbpedia.org/property/dateStart": {
        "@type": "xsd:date",
        "@value": "1993-04-03-08:00"
      },
      "http://semanticweb.org/wiki/Property:Contains": {
        "@id": "http://dbpedia.org/resource/Bonobo"
      },
      "rdfs:label": {
        "@language": "en",
        "@value": "Pygmy Chimps at Bonobo Road"
      }
    },
    {
      "@id": "http://dbpedia.org/resource/Bonobo",
      "@type": [
        "http://dbpedia.org/ontology/Eukaryote",
        "http://dbpedia.org/ontology/Mammal",
        "http://dbpedia.org/ontology/Animal"
      ],
      "foaf:depiction": { "@id": "http://upload.wikimedia.org/wikipedia/commons/a/a6/Bonobo-04.jpg" },
      "foaf:name": {
        "@language": "en",
        "@value": "Bonobos"
      },
      "rdfs:comment": {
        "@language": "en",
        "@value": "The bonobo, Pan paniscus, previously called the pygmy chimpanzee and less often, the dwarf or gracile chimpanzee, is a great ape and one of the two species making up the genus Pan; the other is Pan troglodytes, or the common chimpanzee. Although the name \"chimpanzee\" is sometimes used to refer to both species together, it is usually understood as referring to the common chimpanzee, while Pan paniscus is usually referred to as the bonobo."
      },
      "rdfs:seeAlso": {
        "@id": "http://eol.org/pages/326448/overview"
      }
    },
    {
      "@id": "http://dbpedia.org/resource/Columbus_Zoo_and_Aquarium",
      "@type": "http://example.com/Zoo",
      "http://semanticweb.org/wiki/Property:Contains": {
        "@id": "http://dbpedia.org/resource/Bonobo"
      },
      "rdfs:label": {
        "@language": "en",
        "@value": "Columbus Zoo and Aquarium"
      }
    },
    {
      "@id": "http://dbpedia.org/resource/San_Diego_Zoo",
      "@type": "http://example.com/Zoo",
      "http://dbpedia.org/resource/Exhibit": { "@id": "_:t1" },
      "http://semanticweb.org/wiki/Property:Contains": {
        "@id": "http://dbpedia.org/resource/Bonobo"
      },
      "rdfs:label": {
        "@language": "en",
        "@value": "San Diego Zoo"
      },
      "vcard:adr": { "@id": "_:t0" }
    }
  ]
}
                                            

Listing 2.6 - Apache Directives

# Directives to ensure RDF files are served as the appropriate Content-Type
AddType text/turtle .ttl
AddType application/rdf+xml .rdf
AddType application/ld+json .jsonld
AddType application/N-Triples .nt
                                            

Listing 2.7 - HTTP headers added to a rile served with Apache's mod_asis

Content-Type: text/turtle

@prefix foaf: <http://xmlns.com/foaf/0.1/> .

<http://3Roundstones.com/dave/#me> 
  a foaf:Person .
...
                                            

Listing 3.1 - ProductDB.org data for Star Wars: Episode I – The Phantom Menace in Turtle format

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix ns0: <http://dbpedialite.org/things/50793#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix ns1: <http://www.rottentomatoes.com/m/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix dct: <http://purl.org/dc/terms/> .

<http://productdb.org/groups/421600120915> 
owl:sameAs   <http://data.linkedmdb.org/resource/film/69> ,
<http://rdf.freebase.com/ns/en.star_wars_episode_i_the_phantom_menace> ,
<http://dbpedia.org/resource/Star_Wars_Episode_I:_The_Phantom_Menace> ,

ns0:thing ; 
foaf:isPrimaryTopicOf <http://www.imdb.com/title/tt0120915/> ,
<http://www.netflix.com/Movie/70003791> ,
ns1:star_wars_episode_i_the_phantom_menace ,       
<http://en.wikipedia.org/wiki/Star_Wars_Episode_I:_The_Phantom_Menace> ,
<http://en.wikipedia.org/wiki/index.HTML?curid=50793> ,
<http://www.moodb.net/movie.asp?id=0000217> ;
rdfs:label "Star Wars: Episode I - The Phantom Menace" .
<http://productdb.org/gtin/00024543023913> dct:isVersionOf  <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00010232008374> dct:isVersionOf <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00391772364227> dct:isVersionOf <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00321337023526> dct:isVersionOf <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00039036007375> dct:isVersionOf <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00024543023937> dct:isVersionOf <http://productdb.org/groups/421600120915> .
<http://productdb.org/gtin/00712626010272> dct:isVersionOf <http://productdb.org/groups/421600120915> .
                                            

Listing 3.2 - A Python script for aggregating RDF data for HTML display

#! /usr/bin/python

import rdflib
import html5lib

output = open("output.HTML", "w")

productDBGraph = rdflib.Graph()
productDBResult = productDBGraph.parse('http://productdb.org/gtin/00681326152002.ttl', 
    format='turtle')

bestBuyGraph = rdflib.Graph()
bestBuyResult = bestBuyGraph.parse('http://purl.org/net/BestBuyDarthVaderClock',
    format='rdfa')
print >>output, """                            

    Product Information


"""

print >>output, ""

for sub, pred, obj in productDBGraph:
    print >>output, "" % (sub, pred, obj)
    
for sub, pred, obj in bestBuyGraph:
    print >>output, "" % (sub, pred, obj)

print >>output, """
SubjectPredicateObject
%s%s%s
%s%s%s
"""

Listing 4.1 - Sample FOAF profile for Anakin Skywalker, aka Darth Vader


                                            

Listing 4.2 - Enhanced FOAF profile modeling the foaf:knows relationship


                                            

Listing 4.3 - Enhanced FOAF profile modeling the foaf:knows relationship


                                            

Listing 4.4 - FOAF profile as generated by 3 Round Stones FOAF Profile Generator


                                            

Listing 4.5 - Example of using the WGS84 Basic Geo Vocabulary


                                            

Listing 4.6 - Enhanced FOAF profile applying foaf:img and rel:spouseOf


                                            

Listing 4.7 - Source code for defining wish list vocabulary


                                            

Listing 4.8 - FOAF profile with link to wish list


                                            

Listing 4.9 - Sample wish list document


                                            

Listing 4.10 - Sample wish list document


                                            

Listing 5.1 - SPARQL query to find people’s locations

prefix foaf: <http://xmlns.com/foaf/0.1/>
prefix pos: <http://www.w3.org/2003/01/geo/wgs84_pos#>

select ?name ?latitude ?longitude
from <http://3roundstones.com/dave/me.rdf>
from <http://semanticweb.org/wiki/Special:ExportRDF/Michael_Hausenblas>
where {
  ?person foaf:name ?name ;
          foaf:based_near ?near .
  ?near pos:lat ?latitude ; 
        pos:long ?longitude .
}
LIMIT 10
                                            

Listing 5.2 - SPARQL query to find FOAF friends

prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix foaf: <http://xmlns.com/foaf/0.1/>

select ?name ?url
where {
  ?person rdfs:seeAlso ?url ;
          foaf:name ?name .
}
                                            

Listing 5.3 - Setting up ARQ

# For Unix-like systems, including Linux and OS X:
$ export ARQROOT='/Applications/ARQ-2.8.8'
$ /Applications/ARQ-2.8.8/bin/arq –h

# For Windows:
set ARQROOT=c:\MyProjects\ARQ
c:\MyProjects\ARQ\bat\arq.bat /h
                                            

Listing 5.4 - Running a SPARQL query from the command line

$ /Applications/ARQ-2.8.8/bin/arq --query foaf.rq --data foaf.rdf
                                            

Listing 5.5 - Running a SPARQL query from the command line with multiple data files

$ arq --query foafvcard.rq --data foaf.rdf --data vcard.ttl
                                            

Listing 5.6 - A SPARQL query that combines FOAF and vCard data

prefix foaf: <http://xmlns.com/foaf/0.1/>
prefix vcard: <http://www.w3.org/2006/vcard/ns#>

select ?name ?city ?state
where {
  ?person foaf:name ?name ;
          vcard:adr ?address .
  ?address vcard:locality ?city ;
          vcard:region ?state .
}
                                            

Listing 5.7 - Running a remote SPARQL query from the command line

$ /Applications/ARQ-2.8.8/bin/arq --query livefoaf.rq
                                            

Listing 5.8 - Query the rdf:types a server holds

select distinct ?Concept
where {
  [ ] a ?Concept
}
                                            

Listing 5.9 - An example of a URL-encoded SPARQL query

http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select+distinct+%3FConcept+where+%7B%5B%5D+a+%3FConcept%7D&format=text%2Fhtml&timeout=0
                                            

Listing 5.10 - Introducing OPTIONAL

prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix foaf: <http://xmlns.com/foaf/0.1/>

select ?name ?url
where { 
  ?person foaf:name ?name .
  OPTIONAL { ?person rdfs:seeAlso ?url }
}
                                            

Listing 5.11 - Introducing ORDER BY and LIMIT

select ?link
where {
  <http://dbpedia.org/resource/Linked_Data>
            <http://dbpedia.org/ontology/wikiPageExternalLink> ?link .
} order by ?link limit 10
                                            

Listing 5.12 - Introducing COUNT

select (count(?abstract) as ?count)
where {
  <http://dbpedia.org/resource/Linked_Data> dbpedia-owl:abstract ?abstract .
}
                                            

Listing 5.13 - Introducing FILTERs

select ?abstract
where {
  <http://dbpedia.org/resource/Linked_Data> dbpedia-owl:abstract ?abstract .
  FILTER (lang(?abstract) = "en")
}
                                            

Listing 5.14 - An ASK query

ask
where {
  <http://dbpedia.org/resource/Linked_Data> dbpedia-owl:abstract ?abstract .
}
                                            

Listing 5.15 - A DESCRIBE query

describe <http://dbpedia.org/resource/Linked_Data>
                                            

Listing 5.16 - A CONSTRUCT query

construct {
  <http://dbpedia.org/resource/Linked_Data> ?p ?o
}
where {
  <http://dbpedia.org/resource/Linked_Data> ?p ?o .
  filter langMatches( lang(?title), "EN" )
}
                                            

Listing 5.17 - A SPARQL INSERT

PREFIX dc: <http://purl.org/dc/elements/1.1/>
INSERT DATA
{ 
  <http://www.linkeddatadeveloper.com/> dc:title "Linked Data" ;
                         dc:creator "David Wood" ;
                         dc:creator "Marsha Zaidman" ;
                         dc:creator "Luke Ruth" ;
                         dc:creator "Michael Hausenblas" .

}
                                            

Listing 5.18 - SPARQL results in XML format for the query in listing 5.2


                                            

Listing 5.19 - SPARQL results in JSON format for the query in listing 5.2

{
  "head": {
    "vars": [ "name" , "url" ]
  } ,
  "results": {
    "bindings": [
      {
        "name": { "type": "literal" , "value": "Michael Hausenblas" } ,
        "url": { "type": "uri" , "value": "http://semanticweb.org/wiki/Special:ExportRDF/Michael_Hausenblas" }
      }
    ]
  }
}
                                            

Listing 5.20 - SPARQL query to find people's locations

prefix foaf: <http://xmlns.com/foaf/0.1/>
prefix pos: <http://www.w3.org/2003/01/geo/wgs84_pos#>

SELECT ?name ?latitude ?longitude
FROM <http://3roundstones.com/dave/me.rdf>
FROM <http://semanticweb.org/wiki/Special:ExportRDF/Michael_Hausenblas>
WHERE {
  ?person foaf:name ?name ;
          foaf:based_near ?near .
  ?near pos:lat ?latitude ;
        pos:long ?longitude .
}
                                            

Listing 5.21 - Execute the FOAF map query and save as JSON

$ /Applications/ARQ-2.8.8/bin/arq --query foafmap.rq --results JSON > foafmap.js
                                            

Listing 5.22 - The FOAF map HTML structure


                                            

Listing 5.23 - JavaScript libraries for the FOAF map web page


                                            

Listing 5.24 - JavaScript function to draw the table on the FOAF map web page


                                            

Listing 5.25 - JavaScript function to draw the map on the FOAF map web page


                                            

Listing 5.26 - JavaScript functions to generate random color markers on the FOAF map web page

// Thanks to Jim Bumgardner's color tutorial:
// http://krazydad.com/tutorials/makecolors.php
function chooseColor () {
    var frequency = .3;
    var randomNumber = Math.floor(Math.random() * 32)
    red   = Math.sin(frequency * randomNumber + 0) * 127 + 128;
    green = Math.sin(frequency * randomNumber + 2) * 127 + 128;
    blue  = Math.sin(frequency * randomNumber + 4) * 127 + 128;
    return RGB2Color(red,green,blue);
}

function RGB2Color (r,g,b) {
    return '0x' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);
}

function byte2Hex (n) {
    var nybHexString = "0123456789ABCDEF";
    return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
}
                                            

Listing 6.1 - An HTML description without embedded RDFa


                                            

Listing 6.2 - HTML sample with RDFa markup from the FOAF vocabulary


                                            

Listing 6.3 - Bulleted list excerpt


                                            

Listing 6.4 - Turtle generated from listing 6.2 RDFa enhanced HTML

@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdfa: <http://www.w3.org/ns/rdfa#> .
@prefix rel: <http://purl.org/vocab/relationship/> .

<http://paprika.umw.edu/~marsha/starwars/foaf.ttl> rdfa:usesVocabulary foaf: .

<http://paprika.umw.edu/~marsha/starwars/foaf.ttl#me> a foaf:Person;
    rel:spouseOf "Padme ";
    foaf:family_name "Skywalker";
    foaf:gender "male";
    foaf:givenname "Anakin";
    foaf:homepage <http://www.imdb.com/character/ch0000005/bio>;
    foaf:img <http://www.starwars.com/img/explore/encyclopedia/characters/anakinskywalker_detail.png>;
    foaf:knows [ a foaf:Person;
            foaf:homepage <http://live.dbpedia.org/page/Obi-Wan_Kenobi>;
            foaf:mbox_sha1sum "aadfbacb9de289977d85974fda32baff4b60ca86";
            foaf:name "Obi-Wan Kenobi" ],
        "Padme ",
        [ a foaf:Person;
            foaf:homepage <http://www.imdb.com/character/ch0000005/bio>;
            foaf:mbox_sha1sum "cc77937087f686e222bcf1194fb8c671d8591e00";
            foaf:name "Darth Vader " ],
        "Luke Skywalker ";
    foaf:mbox_sha1sum "cc77937087f686e222bcf1194fb8c671d8591e00";
    foaf:name "Anakin Skywalker ";
    foaf:nick " The Chosen One ";
    foaf:phone "866-555-1212";
    foaf:title "Jedi " .

<https://www.facebook.com/pages/Darth-Vader/10959490906484> a foaf:account .
                                            

Listing 6.5 - Basic HTML without GoodRelations markup


                                            

Listing 6.6 - Sample HTML using GoodRelations


                                            

Listing 6.7 - Excerpt showing centralization of prefix information


                                            

Listing 6.8 - Excerpt of company information


                                            

Listing 6.9 - Excerpt of product information


                                            

Listing 6.10 - Excerpt showing annotation of an individual product review


                                            

Listing 6.11 - Turtle statements derived from listing 6.6


                                            

Listing 6.12 - Basic HTML


                                            

Listing 6.13 - HTML sample with RDFa mark-up from the schema.org vocabulary


                                            

Listing 6.14 - Resulting Turtle from HTML annotated with schema.org vocabulary


                                            

Listing 6.15 - Sample SPARQL query to select reviews


                                            

Listing 7.1 -


                                            

Listing 7.2 -


                                            

Listing 7.3 -


                                            

Listing 7.4 -


                                            

Listing 7.5 -

                                           
#! /usr/bin/python

import os
import urllib
import urllib2
from urllib2 import Request, urlopen, URLError
import csv
from cStringIO import StringIO
import xml.etree.ElementTree as ET
from datetime import date
import subprocess
from time import sleep

# Variables, input, and output files
input = open('LD_Book_VA_ZipCodes.txt', 'r') 
output = open('weatherData.ttl', 'w') 
today = date.today().strftime("%m-%d-%y")

print "\nStarting Fuseki..."
os.chdir("/Users/LukeRuth/Desktop/jena-fuseki-0.2.5/")  
args1 = ['./fuseki-server', '--update', '--mem', '/ds']
subprocess.Popen(args1)

sleep(10)  
print "\n"

print >>output, "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ."
print >>output, "@prefix wh: <http://www.example.com/WeatherHealth/Schema#> .\n"

# Cycle through every zip code in the input file
for line in input: 
    zip = line
	zip = zip.rstrip()
	
	noaaQuery = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?ZIP CodeList=" + zip + "&product=time-series&maxt=maxt&mint=mint"
	epaQuery = "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/" + zip + "/CSV"
	 
	noaaReq = urllib2.Request(url=noaaQuery)
	try:
		noaaContents = urllib2.urlopen(noaaReq).read()
	except URLError, e:
		if hasattr(e, 'reason'):
			print'We failed to reach a server.'
			print 'Reason: ', e.reason
		elif hasattr(e, 'code'):
			print 'The server couldn\'t fulfill the request.'
			print 'Error code: ', e.code
	else:
		# Parse and obtain desired NOAA xml contents
		root = ET.fromstring(noaaContents)
		for temperature in root.findall(".//value/..[@type='maximum']"):
			maxTemp = temperature.find('value').text
		
		for temperature in root.findall(".//value/..[@type='minimum']"):
			minTemp = temperature.find('value').text
	 
	try:
		epaContents = urllib2.urlopen(epaQuery).read()
	except URLError, e:
		if hasattr(e, 'reason'):
			print'We failed to reach a server.'
			print 'Reason: ', e.reason
		elif hasattr(e, 'code'):
			print 'The server couldn\'t fulfill the request.'
			print 'Error code: ', e.code
	else:
		epaContents = epaContents.rstrip()
		# Loop through EPA CSV file and assign values to variables
		reader = csv.DictReader(StringIO(epaContents), delimiter=',')
		for row in reader:
			uvValue = row['UV_VALUE']
			uvAlert = row['UV_ALERT']
			   
	print >>output, "<http://www.example.com/WeatherHealth/ZipCodes/" + zip + "> wh:weather_for <http://www.example.com/WeatherHealth/ZipCodes/" + zip + "/" + today + "> ."
	print >>output, "<http://www.example.com/WeatherHealth/ZipCodes/" + zip + "/" + today + ">"
	
	# Only print values that are present
	if (maxTemp):
		print >>output, " wh:max_temp " + maxTemp
	if (minTemp):
		print >>output, " ; wh:min_temp " + minTemp
	if (uvValue):
		print >>output, " ; wh:uv_value " + uvValue
		
	if (uvAlert == "0"):
		print >>output, " ; wh:uv_alert \"False\""
	elif (uvAlert == "1"):
	 	print >>output, " ; wh:uv_alert \"True\""
	 	
	print >>output, ". \n";

# Close zip code input and Turtle output files
input.close()
output.close()
 
print "Loading Data..."
args2 = ["./s-put", "http://localhost:3030/ds/data", "default", "/Users/LukeRuth/Desktop/LinkedData_WeatherHealthApp/Chapter7/weatherData.ttl"]
subprocess.Popen(args2)

sleep(10) 
print "\n"
 
print "Executing Query..."
args3 = ["./s-query", "--service", "http://localhost:3030/ds/query", "SELECT ?day ?maxTemp ?uvValue WHERE { ?day <http://www.example.com/WeatherHealth/Schema#max_temp> ?maxTemp ; <http://www.example.com/WeatherHealth/Schema#uv_value> ?uvValue . } LIMIT 1"]
subprocess.Popen(args3)

sleep(10) 
print "\nScript Complete.\n"
                                            

Listing 8.1 -


                                            

Listing 8.2 -


                                            

Listing 8.3 -


                                            

Listing 8.4 -


                                            

Listing 8.5 -


                                            

Listing 8.6 -


                                            

Listing 8.7 -


                                            

Listing 8.8 -


                                            

Listing 8.9 -


                                            

Listing 8.10 -


                                            

Listing 8.11 -


                                            

Listing 9.1 -


                                            

Listing 9.2 -


                                            

Listing 9.3 -


                                            

Listing 9.4 -


                                            

Listing 9.5 -


                                            

Listing 9.6 -


                                            

Listing 9.7 -


                                            

Listing 9.8 -


                                            

Listing 9.9 -


                                            

Listing 9.10 -


                                            

Listing 9.11 -


                                            

Listing 9.12 -


                                            

Listing 9.13 -


                                            

The Nitty Gritty

Current Errata

This document is the most up to date source of identified errata in the book. Please check this document before submitting issues to the Author Forum.

Submit Comments

Post to the Author Forum at Manning.com if you find typos or would like to make suggestions for future editions of the book.

Developer Information

This site was developed using Callimachus, the Open Source Linked Data framework described in the book. To learn more about it check out CallimachusProject.org.