SlideShare une entreprise Scribd logo
1  sur  16
Scalable and Reactive
Programming for Semantic
Web Developers
Jean-Paul Calbimonte
LSIR EPFL
Developers Workshop. Extended Semantic Web Conference ESWC 2015
Portoroz, 31.05.2015
@jpcik
Semantic Web Devs
2
Have fun
Love challenges
Need cool tools
Sesame
Scala: Functions and Objects
3
JVM language
Both object and functional oriented
Easy Java-interop
Reuse Java libraries
Growing community
RDF in Jena: in Scala
String personURI = "http://somewhere/JohnSmith";
Model model = ModelFactory.createDefaultModel();
model.createResource(personURI).addProperty(VCARD.FN,"John Smith");
Type inference
Not too useful
; and ()
4
Terser & compact code
Type-safe DSL
Compiler takes care
val personURI = "http://somewhere/JohnSmith"
val model = ModelFactory.createDefaultModel
model.createResource(personURI).addProperty(VCARD.FN,"John Smith")
sw:JohnSmith “John Smith”
vcard:FN
val personURI = "http://somewhere/JohnSmith"
implicit val model = createDefaultModel
add(personURI,VCARD.FN->"John Smith")
boilerplate
String converted
to Resource
Some more RDF
5
String personURI = "http://somewhere/JohnSmith";
String givenName = "John";
String familyName = "Smith";
String fullName = givenName + " " + familyName;
Model model = ModelFactory.createDefaultModel();
model.createResource(personURI)
.addProperty(VCARD.FN,fullName)
.addProperty(VCARD.N,model.createResource()
.addProperty(VCARD.Given,givenName)
.addProperty(VCARD.Family,familyName));
val personURI = "http://somewhere/JohnSmith"
val givenName = "John"
val familyName = "Smith"
val fullName = s"$givenName $familyName"
implicit val model = createDefaultModel
add(personURI,VCARD.FN->fullName,
VCARD.N ->add(bnode,VCARD.Given -> givenName,
VCARD.Family->familyName))
sw:JohnSmith
“John Smith”
vcard:FN
_:n
“John”
“Smith”vcard:N
vcard:Given
vcard:Family
Blank node
Scala DSLs customizable
Predicate-objects are pairs
Some more RDF in Jena
6
implicit val m=createDefaultModel
val ex="http://example.org/"
val alice=iri(ex+"alice")
val bob=iri(ex+"bob")
val charlie=iri(ex+"charlie")
alice+(RDF.`type`->FOAF.Person,
FOAF.name->"Alice",
FOAF.mbox-
>iri("mailto:alice@example.org"),
FOAF.knows->bob,
FOAF.knows->charlie, FOAF.knows->bnode)
bob+ (FOAF.name->"Bob",
FOAF.knows->charlie)
charlie+(FOAF.name->"Charlie",
FOAF.knows->alice)
Still valid Jena RDF
You can do it even nicer
Exploring an RDF Graph
7
ArrayList<String> names=new ArrayList<String>();
NodeIterator iter=model.listObjectsOfProperty(VCARD.N);
while (iter.hasNext()){
RDFNode obj=iter.next();
if (obj.isResource())
names.add(obj.asResource()
.getProperty(VCARD.Family).getObject().toString());
else if (obj.isLiteral())
names.add(obj.asLiteral().getString());
}
val names=model.listObjectsOfProperty(VCARD.N).map{
case r:Resource=>
r.getProperty(VCARD.Family).obj.toString
case l:Literal=>
l.getString
}
Imperative iteration of collections
Type-based conditional execution
Type casting
Case type
Map applied to operators
8
Query with SPARQL
9
val queryStr = """select distinct ?Concept
where {[] a ?Concept} LIMIT 10"""
val query = sparql(queryStr)
query.serviceSelect("http://dbpedia.org/sparql").foreach{implicit qs=>
println(res("Concept").getURI)
}
val f=Future(query.serviceSelect("http://es.dbpedia.org/sparql")).fallbackTo(
Future(query.serviceSelect("http://dbpedia.org/sparql")))
f.recover{
case e=> println("Error "+e.getMessage)
}
f.map(_.foreach{implicit qs=>
println(res("Concept").getValue)
})
Remote SPARQL endpoint
Simplified access to
Query solutions
Futures: asnyc execution
Non blocking code
Fallback alternative execution
Actor Model
10
Actor
1
Actor
2
m
No shared mutable state
Avoid blocking operators
Lightweight objects
Loose coupling
communicate
through messages
mailbox
state
behavior
non-blocking response
send: fire-forget
Implementations: e.g. Akka for Java/Scala
Pare
nt
Actor
1
Supervision
hierarchy
Supervision
Actor
2
Actor
4
X
Actor
2
Act
or1
Act
or2
m
Act
or3
Act
or4
m
m
Remoting
Reactive Systems
Event-Driven
Jonas Boner. Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems. 2013.
Events:
reactto
ScalableLoad:
ResilientFailure:
ResponsiveUsers:
11
RDF Streams: Actors
12
val sys=ActorSystem.create("system")
val consumer=sys.actorOf(Props[RdfConsumer])
class Streamer extends StreamRDF{
override def triple(triple:Triple){
consumer ! triple
}
}
class RdfConsumer extends Actor{
def receive= {
case t:Triple =>
if (t.predicateMatches(RDF.‘type‘))
println(s"received triple $t")
}
RDF consumer
Actor receive method
Implements behavior
Message-passing model
RDF producer
Async message passing
Web RDF Services
13
GET /containers/:containerid/ org.rsp.ldp.ContainerApp.retrieve(containerid:String)
POST /containers/:containerid/ org.rsp.ldp.ContainerApp.add(containerid:String)
object ContainerApp extends Controller {
def retrieve(id:String) = Action.async {implicit request=>
val sw=new StringWriter
val statements=m.listStatements(iri(prefix+id+"/"),null,null)
val model=createDefaultModel
statements.foreach(i=>model.add(i))
model.write(sw, "TURTLE")
Future(Ok(sw.toString).as("text/turtle").withHeaders(
ETAG->tag,
ALLOW->"GET,POST"
))
}
Routing rules
Controller returns RDF async
OWLAPI: reasoning
14
val onto=mgr.createOntology
val artist=clazz(pref+"Artist")
val singer=clazz(pref +"Singer")
onto += singer subClassOf artist
val reasoner = new RELReasonerFactory.createReasoner(onto)
val elvis=ind(pref+"Elvis")
reasoner += elvis ofClass singer
reasoner.reclassify
reasoner.getIndividuals(artist) foreach{a=>
println(a.getRepresentativeElement.getIRI)
}
Creating OWL classes
Declaring class relationships
Declare instances
How is it done?
15
object OwlApiTips{
implicit class TrowlRelReasoner(reasoner:RELReasoner){
def += (axiom:OWLAxiom)= reasoner.add(Set(axiom)) }
implicit class OwlClassPlus(theClass:OWLClass){
def subClassOf(superclass:OWLClass)(implicit fac:OWLDataFactory)=
fac.getOWLSubClassOfAxiom(theClass, superclass) }
implicit class OwlOntologyPlus(onto:OWLOntology){
def += (axiom:OWLAxiom)(implicit mgr:OWLOntologyManager)=
mgr.addAxiom(onto, axiom) }
implicit class OwlIndividualPlus(ind:OWLIndividual){
def ofClass (theclass:OWLClass)(implicit fac:OWLDataFactory)=
fac.getOWLClassAssertionAxiom(theclass, ind) }
implicit def str2Iri(s:String):IRI=IRI.create(s)
object clazz{
def apply(iri:String)(implicit fac:OWLDataFactory)=
fac.getOWLClass(iri) }
object ind{
def apply(iri:String)(implicit fac:OWLDataFactory)=
fac.getOWLNamedIndividual(iri) } }
Muchas gracias!
Jean-Paul Calbimonte
LSIR EPFL
@jpcik

Contenu connexe

Tendances

WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
Katrien Verbert
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
Scala Italy
 

Tendances (20)

2008 11 13 Hcls Call
2008 11 13 Hcls Call2008 11 13 Hcls Call
2008 11 13 Hcls Call
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data World
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and Semantics
 
Semantic Integration with Apache Jena and Stanbol
Semantic Integration with Apache Jena and StanbolSemantic Integration with Apache Jena and Stanbol
Semantic Integration with Apache Jena and Stanbol
 
The Materials Project - Combining Science and Informatics to Accelerate Mater...
The Materials Project - Combining Science and Informatics to Accelerate Mater...The Materials Project - Combining Science and Informatics to Accelerate Mater...
The Materials Project - Combining Science and Informatics to Accelerate Mater...
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Querying Linked Data with SPARQL
Querying Linked Data with SPARQLQuerying Linked Data with SPARQL
Querying Linked Data with SPARQL
 
SPARQL Cheat Sheet
SPARQL Cheat SheetSPARQL Cheat Sheet
SPARQL Cheat Sheet
 
The Materials API
The Materials APIThe Materials API
The Materials API
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Apache Jena Elephas and Friends
Apache Jena Elephas and FriendsApache Jena Elephas and Friends
Apache Jena Elephas and Friends
 
Semantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorialSemantic web meetup – sparql tutorial
Semantic web meetup – sparql tutorial
 
Devoxx
DevoxxDevoxx
Devoxx
 
Information-Rich Programming in F# with Semantic Data
Information-Rich Programming in F# with Semantic DataInformation-Rich Programming in F# with Semantic Data
Information-Rich Programming in F# with Semantic Data
 
Beyond shuffling - Strata London 2016
Beyond shuffling - Strata London 2016Beyond shuffling - Strata London 2016
Beyond shuffling - Strata London 2016
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 

En vedette

Aturansinus
AturansinusAturansinus
Aturansinus
aan72
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Thomas Lockney
 

En vedette (6)

Aturansinus
AturansinusAturansinus
Aturansinus
 
Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)Take a Look at Akka+Java (English version)
Take a Look at Akka+Java (English version)
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
RDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementationsRDF Stream Processing Tutorial: RSP implementations
RDF Stream Processing Tutorial: RSP implementations
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 

Similaire à Scala Programming for Semantic Web Developers ESWC Semdev2015

Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with Scala
WO Community
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 

Similaire à Scala Programming for Semantic Web Developers ESWC Semdev2015 (20)

Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Introduction to Apache Camel
Introduction to Apache CamelIntroduction to Apache Camel
Introduction to Apache Camel
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with Scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Java, what's next?
Java, what's next?Java, what's next?
Java, what's next?
 
Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Developing a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and Spray
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим Клыга
 
Play framework
Play frameworkPlay framework
Play framework
 

Plus de Jean-Paul Calbimonte

Plus de Jean-Paul Calbimonte (20)

Towards Collaborative Creativity in Persuasive Multi-agent Systems
Towards Collaborative Creativity in Persuasive Multi-agent SystemsTowards Collaborative Creativity in Persuasive Multi-agent Systems
Towards Collaborative Creativity in Persuasive Multi-agent Systems
 
A Platform for Difficulty Assessment and Recommendation of Hiking Trails
A Platform for Difficulty Assessment andRecommendation of Hiking TrailsA Platform for Difficulty Assessment andRecommendation of Hiking Trails
A Platform for Difficulty Assessment and Recommendation of Hiking Trails
 
Stream reasoning agents
Stream reasoning agentsStream reasoning agents
Stream reasoning agents
 
Decentralized Management of Patient Profiles and Trajectories through Semanti...
Decentralized Management of Patient Profiles and Trajectories through Semanti...Decentralized Management of Patient Profiles and Trajectories through Semanti...
Decentralized Management of Patient Profiles and Trajectories through Semanti...
 
Personal Data Privacy Semantics in Multi-Agent Systems Interactions
Personal Data Privacy Semantics in Multi-Agent Systems InteractionsPersonal Data Privacy Semantics in Multi-Agent Systems Interactions
Personal Data Privacy Semantics in Multi-Agent Systems Interactions
 
RDF data validation 2017 SHACL
RDF data validation 2017 SHACLRDF data validation 2017 SHACL
RDF data validation 2017 SHACL
 
SanTour: Personalized Recommendation of Hiking Trails to Health Pro files
SanTour: Personalized Recommendation of Hiking Trails to Health ProfilesSanTour: Personalized Recommendation of Hiking Trails to Health Profiles
SanTour: Personalized Recommendation of Hiking Trails to Health Pro files
 
Multi-agent interactions on the Web through Linked Data Notifications
Multi-agent interactions on the Web through Linked Data NotificationsMulti-agent interactions on the Web through Linked Data Notifications
Multi-agent interactions on the Web through Linked Data Notifications
 
The MedRed Ontology for Representing Clinical Data Acquisition Metadata
The MedRed Ontology for Representing Clinical Data Acquisition MetadataThe MedRed Ontology for Representing Clinical Data Acquisition Metadata
The MedRed Ontology for Representing Clinical Data Acquisition Metadata
 
Linked Data Notifications for RDF Streams
Linked Data Notifications for RDF StreamsLinked Data Notifications for RDF Streams
Linked Data Notifications for RDF Streams
 
Fundamentos de Scala (Scala Basics) (español) Catecbol
Fundamentos de Scala (Scala Basics) (español) CatecbolFundamentos de Scala (Scala Basics) (español) Catecbol
Fundamentos de Scala (Scala Basics) (español) Catecbol
 
Connecting Stream Reasoners on the Web
Connecting Stream Reasoners on the WebConnecting Stream Reasoners on the Web
Connecting Stream Reasoners on the Web
 
Query Rewriting in RDF Stream Processing
Query Rewriting in RDF Stream ProcessingQuery Rewriting in RDF Stream Processing
Query Rewriting in RDF Stream Processing
 
Toward Semantic Sensor Data Archives on the Web
Toward Semantic Sensor Data Archives on the WebToward Semantic Sensor Data Archives on the Web
Toward Semantic Sensor Data Archives on the Web
 
Detection of hypoglycemic events through wearable sensors
Detection of hypoglycemic events through wearable sensorsDetection of hypoglycemic events through wearable sensors
Detection of hypoglycemic events through wearable sensors
 
RDF Stream Processing and the role of Semantics
RDF Stream Processing and the role of SemanticsRDF Stream Processing and the role of Semantics
RDF Stream Processing and the role of Semantics
 
The Schema Editor of OpenIoT for Semantic Sensor Networks
The Schema Editor of OpenIoT for Semantic Sensor NetworksThe Schema Editor of OpenIoT for Semantic Sensor Networks
The Schema Editor of OpenIoT for Semantic Sensor Networks
 
XGSN: An Open-source Semantic Sensing Middleware for the Web of Things
XGSN: An Open-source Semantic Sensing Middleware for the Web of ThingsXGSN: An Open-source Semantic Sensing Middleware for the Web of Things
XGSN: An Open-source Semantic Sensing Middleware for the Web of Things
 
X-GSN in OpenIoT SummerSchool
X-GSN in OpenIoT SummerSchoolX-GSN in OpenIoT SummerSchool
X-GSN in OpenIoT SummerSchool
 
GSN Global Sensor Networks for Environmental Data Management
GSN Global Sensor Networks for Environmental Data ManagementGSN Global Sensor Networks for Environmental Data Management
GSN Global Sensor Networks for Environmental Data Management
 

Dernier

scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
INTERRUPT CONTROLLER 8259 MICROPROCESSOR
INTERRUPT CONTROLLER 8259 MICROPROCESSORINTERRUPT CONTROLLER 8259 MICROPROCESSOR
INTERRUPT CONTROLLER 8259 MICROPROCESSOR
TanishkaHira1
 

Dernier (20)

Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
TMU_GDSC_20240509.pdfTMU_GDSC_20240509.pdf
TMU_GDSC_20240509.pdfTMU_GDSC_20240509.pdfTMU_GDSC_20240509.pdfTMU_GDSC_20240509.pdf
TMU_GDSC_20240509.pdfTMU_GDSC_20240509.pdf
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Working Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdfWorking Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdf
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Independent Solar-Powered Electric Vehicle Charging Station
Independent Solar-Powered Electric Vehicle Charging StationIndependent Solar-Powered Electric Vehicle Charging Station
Independent Solar-Powered Electric Vehicle Charging Station
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Danikor Product Catalog- Screw Feeder.pdf
Danikor Product Catalog- Screw Feeder.pdfDanikor Product Catalog- Screw Feeder.pdf
Danikor Product Catalog- Screw Feeder.pdf
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
Fundamentals of Internet of Things (IoT) Part-2
Fundamentals of Internet of Things (IoT) Part-2Fundamentals of Internet of Things (IoT) Part-2
Fundamentals of Internet of Things (IoT) Part-2
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Presentation on Slab, Beam, Column, and Foundation/Footing
Presentation on Slab,  Beam, Column, and Foundation/FootingPresentation on Slab,  Beam, Column, and Foundation/Footing
Presentation on Slab, Beam, Column, and Foundation/Footing
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To Curves
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
INTERRUPT CONTROLLER 8259 MICROPROCESSOR
INTERRUPT CONTROLLER 8259 MICROPROCESSORINTERRUPT CONTROLLER 8259 MICROPROCESSOR
INTERRUPT CONTROLLER 8259 MICROPROCESSOR
 
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
 

Scala Programming for Semantic Web Developers ESWC Semdev2015

  • 1. Scalable and Reactive Programming for Semantic Web Developers Jean-Paul Calbimonte LSIR EPFL Developers Workshop. Extended Semantic Web Conference ESWC 2015 Portoroz, 31.05.2015 @jpcik
  • 2. Semantic Web Devs 2 Have fun Love challenges Need cool tools Sesame
  • 3. Scala: Functions and Objects 3 JVM language Both object and functional oriented Easy Java-interop Reuse Java libraries Growing community
  • 4. RDF in Jena: in Scala String personURI = "http://somewhere/JohnSmith"; Model model = ModelFactory.createDefaultModel(); model.createResource(personURI).addProperty(VCARD.FN,"John Smith"); Type inference Not too useful ; and () 4 Terser & compact code Type-safe DSL Compiler takes care val personURI = "http://somewhere/JohnSmith" val model = ModelFactory.createDefaultModel model.createResource(personURI).addProperty(VCARD.FN,"John Smith") sw:JohnSmith “John Smith” vcard:FN val personURI = "http://somewhere/JohnSmith" implicit val model = createDefaultModel add(personURI,VCARD.FN->"John Smith") boilerplate String converted to Resource
  • 5. Some more RDF 5 String personURI = "http://somewhere/JohnSmith"; String givenName = "John"; String familyName = "Smith"; String fullName = givenName + " " + familyName; Model model = ModelFactory.createDefaultModel(); model.createResource(personURI) .addProperty(VCARD.FN,fullName) .addProperty(VCARD.N,model.createResource() .addProperty(VCARD.Given,givenName) .addProperty(VCARD.Family,familyName)); val personURI = "http://somewhere/JohnSmith" val givenName = "John" val familyName = "Smith" val fullName = s"$givenName $familyName" implicit val model = createDefaultModel add(personURI,VCARD.FN->fullName, VCARD.N ->add(bnode,VCARD.Given -> givenName, VCARD.Family->familyName)) sw:JohnSmith “John Smith” vcard:FN _:n “John” “Smith”vcard:N vcard:Given vcard:Family Blank node Scala DSLs customizable Predicate-objects are pairs
  • 6. Some more RDF in Jena 6 implicit val m=createDefaultModel val ex="http://example.org/" val alice=iri(ex+"alice") val bob=iri(ex+"bob") val charlie=iri(ex+"charlie") alice+(RDF.`type`->FOAF.Person, FOAF.name->"Alice", FOAF.mbox- >iri("mailto:alice@example.org"), FOAF.knows->bob, FOAF.knows->charlie, FOAF.knows->bnode) bob+ (FOAF.name->"Bob", FOAF.knows->charlie) charlie+(FOAF.name->"Charlie", FOAF.knows->alice) Still valid Jena RDF You can do it even nicer
  • 7. Exploring an RDF Graph 7 ArrayList<String> names=new ArrayList<String>(); NodeIterator iter=model.listObjectsOfProperty(VCARD.N); while (iter.hasNext()){ RDFNode obj=iter.next(); if (obj.isResource()) names.add(obj.asResource() .getProperty(VCARD.Family).getObject().toString()); else if (obj.isLiteral()) names.add(obj.asLiteral().getString()); } val names=model.listObjectsOfProperty(VCARD.N).map{ case r:Resource=> r.getProperty(VCARD.Family).obj.toString case l:Literal=> l.getString } Imperative iteration of collections Type-based conditional execution Type casting Case type Map applied to operators
  • 8. 8
  • 9. Query with SPARQL 9 val queryStr = """select distinct ?Concept where {[] a ?Concept} LIMIT 10""" val query = sparql(queryStr) query.serviceSelect("http://dbpedia.org/sparql").foreach{implicit qs=> println(res("Concept").getURI) } val f=Future(query.serviceSelect("http://es.dbpedia.org/sparql")).fallbackTo( Future(query.serviceSelect("http://dbpedia.org/sparql"))) f.recover{ case e=> println("Error "+e.getMessage) } f.map(_.foreach{implicit qs=> println(res("Concept").getValue) }) Remote SPARQL endpoint Simplified access to Query solutions Futures: asnyc execution Non blocking code Fallback alternative execution
  • 10. Actor Model 10 Actor 1 Actor 2 m No shared mutable state Avoid blocking operators Lightweight objects Loose coupling communicate through messages mailbox state behavior non-blocking response send: fire-forget Implementations: e.g. Akka for Java/Scala Pare nt Actor 1 Supervision hierarchy Supervision Actor 2 Actor 4 X Actor 2 Act or1 Act or2 m Act or3 Act or4 m m Remoting
  • 11. Reactive Systems Event-Driven Jonas Boner. Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems. 2013. Events: reactto ScalableLoad: ResilientFailure: ResponsiveUsers: 11
  • 12. RDF Streams: Actors 12 val sys=ActorSystem.create("system") val consumer=sys.actorOf(Props[RdfConsumer]) class Streamer extends StreamRDF{ override def triple(triple:Triple){ consumer ! triple } } class RdfConsumer extends Actor{ def receive= { case t:Triple => if (t.predicateMatches(RDF.‘type‘)) println(s"received triple $t") } RDF consumer Actor receive method Implements behavior Message-passing model RDF producer Async message passing
  • 13. Web RDF Services 13 GET /containers/:containerid/ org.rsp.ldp.ContainerApp.retrieve(containerid:String) POST /containers/:containerid/ org.rsp.ldp.ContainerApp.add(containerid:String) object ContainerApp extends Controller { def retrieve(id:String) = Action.async {implicit request=> val sw=new StringWriter val statements=m.listStatements(iri(prefix+id+"/"),null,null) val model=createDefaultModel statements.foreach(i=>model.add(i)) model.write(sw, "TURTLE") Future(Ok(sw.toString).as("text/turtle").withHeaders( ETAG->tag, ALLOW->"GET,POST" )) } Routing rules Controller returns RDF async
  • 14. OWLAPI: reasoning 14 val onto=mgr.createOntology val artist=clazz(pref+"Artist") val singer=clazz(pref +"Singer") onto += singer subClassOf artist val reasoner = new RELReasonerFactory.createReasoner(onto) val elvis=ind(pref+"Elvis") reasoner += elvis ofClass singer reasoner.reclassify reasoner.getIndividuals(artist) foreach{a=> println(a.getRepresentativeElement.getIRI) } Creating OWL classes Declaring class relationships Declare instances
  • 15. How is it done? 15 object OwlApiTips{ implicit class TrowlRelReasoner(reasoner:RELReasoner){ def += (axiom:OWLAxiom)= reasoner.add(Set(axiom)) } implicit class OwlClassPlus(theClass:OWLClass){ def subClassOf(superclass:OWLClass)(implicit fac:OWLDataFactory)= fac.getOWLSubClassOfAxiom(theClass, superclass) } implicit class OwlOntologyPlus(onto:OWLOntology){ def += (axiom:OWLAxiom)(implicit mgr:OWLOntologyManager)= mgr.addAxiom(onto, axiom) } implicit class OwlIndividualPlus(ind:OWLIndividual){ def ofClass (theclass:OWLClass)(implicit fac:OWLDataFactory)= fac.getOWLClassAssertionAxiom(theclass, ind) } implicit def str2Iri(s:String):IRI=IRI.create(s) object clazz{ def apply(iri:String)(implicit fac:OWLDataFactory)= fac.getOWLClass(iri) } object ind{ def apply(iri:String)(implicit fac:OWLDataFactory)= fac.getOWLNamedIndividual(iri) } }