-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_manual.html
More file actions
787 lines (573 loc) · 43.7 KB
/
user_manual.html
File metadata and controls
787 lines (573 loc) · 43.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>JPC User Guide</title>
<link rel="stylesheet" href="/styles/publication/sc.tutorial.css" />
<link rel="stylesheet" href="/styles/publication/sc.tooglejs.css" />
<script type="text/javascript" src="/js/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/ace-builds/src-noconflict/ace.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/publication/jquery.tableofcontents.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/publication/jquery.sc.publication.js" charset="utf-8"></script>
<script type="text/javascript">//<![CDATA[
(function ($) {
$(document).ready(function(){
$('#table_of_content_entries').tableOfContents('#content', {startLevel:2, depth: 3});
$.prettifyCodeSnippets("eclipse");
//$.prettifyCodeSnippets("solarized_light");
$.configureFootnotes();
})
})(jQuery);
//]]></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-47515052-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<h1>JPC User Guide</h1>
(Work in progress).
<div id="table_of_content">
<strong>Contents</strong>
<ol id="table_of_content_entries"></ol>
</div>
<div id="content">
<h2>Introduction</h2>
<p>
JPC is a Java-Prolog interoperability library based on the notion of inter-language conversions.
It provides different layers of integration abstractions.
This guide presents the different JPC features supporting the integration of Java-Prolog systems, assuming a general understanding of the <a href="architecture.html" title="JPC architecture">JPC architecture</a>.
</p>
<p>
You will notice that JPC often provides more than one mechanism to accomplish certain tasks.
Typically, a simple straightforward way that is good enough for many small problems, and more sophisticated alternatives that may be more appropriate for complex requirements.
If you are reading this guide for first time, it may be a good idea to start with the simpler alternatives (always presented first) and leave the more complex options for later.
</p>
<p>
Several examples in this section refer to the <a href="/london_underground.html" title="London underground example">London underground case study</a>.
In order to download and try these examples, please refer to the <a href="installation_guide.html#installingJpcExamples" title="JPC Installation guide">JPC installation guide</a>.
</p>
<h2>Creating Prolog Engines</h2>
<p>
JPC provides an abstraction of a Prolog engine that can interoperate with concrete Prolog engines by means of drivers.
This section describes how to instantiate such engines.
</p>
<h3>Explicit Instantiation</h3>
<p>
The easiest way to instantiate a Prolog engine is by explicitly referencing a JPC driver.
For example, to instantiate a JPC engine using the <a href="installation_guide.html#pdtDriver" title="PDT-based driver">PDT-based driver</a> we could write:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
PrologEngine engine = new PdtConnectorDriver().createPrologEngine();
</pre></div>
<p>
This approach, although straightforward and good enough for many scenarios, causes a strong coupling between an application and a concrete driver.
An alternative is presented below.
</p>
<h3>Categorized Prolog Engines</h3>
<p>
Several techniques and conventions presented in this section are inspired on <a href="http://logging.apache.org/log4j/1.2/" title="Apache log4j">Apache log4j</a>, a well-known logging library.
</p>
<p>
JPC allows to easily categorize an <q>engine space</q> (i.e., the space of all possible Prolog engines) according to some developer-chosen criteria.
This approach allows to decouple a Java program from concrete engine implementations and provides fine grained control on the Prolog engines that should be used to accomplish a given task.
</p>
<p>
Using this technique, engines are categorized hierarchically following a naming rule.
In this hierarchy, a name <code>"org.jpc"</code> is said to be the ancestor of the name <code>"org.jpc.Jpc"</code>.
An engine categorized by means of a name will be inherited, unless overridden, by any of its name descendants.
This categorization is illustrated by the figure below.
</p>
<div class="divImg">
<img src="img/jpc/jpc_named_hierarchy.svg" alt="Named categorization for engines." style="padding-bottom:0.5em;" height="243" />
<div id="imglabel:jpc_named_hierarchy" >Fig 1. - A named categorization for engines.</div>
</div>
<p>
An engine space can be defined either programmatically or by means of a settings file.
The latter is the JPC recommended approach.
</p>
<p>
A JPC configuration can be represented (e.g., in a settings file) as a <a href="http://json.org/" title="JSON">JSON</a> object.
One of the attributes of this configuration object is <code>engines</code>, a list of engine configurations.
The following JPC configuration specifies a Logtalk compatible Prolog engine categorized under the name <code>"org.jpc"</code>.
</p>
<div class="codeEditor"><pre data-editor="json" data-show-gutter="true">
{
"engines": [
{
"id": "pdt",
"categoryNames": ["org.jpc"],
"factoryClass": "org.jpc.engine.pdtconnector.PdtConnectorDriver",
"profile": "org.jpc.engine.profile.LogtalkEngineProfile"
}
]
}</pre></div>
<p>
Each engine configuration has the following attributes:
</p>
<div class="divList">
<ul>
<li><code>id</code>: The identifier of this engine configuration. This attribute is optional if the <code>categoryNames</code> attribute is specified.</li>
<li><code>categoryNames</code>: A list of category names to which this engine configuration applies. This attribute is optional if the <code>id</code> attribute is specified.</li>
<li><code>factoryClass</code>: A <a href="http://en.wikipedia.org/wiki/Factory_pattern" title="Factory pattern">factory</a> of Prolog engines (usually a JPC driver) associated to this engine configuration.</li>
<li><code>factoryMethod</code>: A (static or instance) method in the factory class that creates a Prolog engine. This attribute is optional. If no specified, the factory class should implement the <a href="/javadocs/org/jpc/engine/prolog/driver/PrologEngineFactory.html" title="PrologEngineFactory class"><code>PrologEngineFactory</code></a> interface.</li>
<li><code>profile</code>: A <a href="http://en.wikipedia.org/wiki/Decorator_pattern" title="Decorator pattern">decorator</a> that may configure the Prolog engine the first time it is instantiated. It must be a class implementing the <a href="/javadocs/org/jpc/engine/profile/PrologEngineProfile.html" title="PrologEngineProfile class"><code>PrologEngineProfile</code></a> interface. This attribute is optional.</li>
</ul>
</div>
<p>
Although Prolog engines can be categorized by means of any name, the JPC convention is to categorize them according to the fully qualified name of the class or package where they are used.
Therefore, an engine categorized for the <code>org.jpc</code> package will be used in the <code>org.jpc.Jpc</code> class unless overridden (e.g., if another engine has been categorized for the name <code>"org.jpc.Jpc"</code>).
An attempt to categorize a Prolog engine under an already used category name will result in an exception.
To obtain a Prolog engine in an arbitrary class, you need to write:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
import static org.jpc.engine.prolog.PrologEngines.getPrologEngine;
...
getPrologEngine(getClass().getCanonicalName()); //returns a Prolog engine categorized for this class fully qualified name.
//or just:
getPrologEngine(getClass());</pre></div>
<p>
Alternatively, a Prolog engine may be instantiated by means of the <code>id</code> of an engine configuration, like:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
import static org.jpc.engine.prolog.PrologEngines.getPrologEngineById;
...
getPrologEngineById("pdt");</pre></div>
<p>
The engines obtained in the previous examples are instantiated from the default settings file <code>jpc.settings</code> in the root package.
Alternatively, engines can be instantiated from an arbitrary settings file as in this example:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
import org.jpc.util.config.EngineConfigurationManager;
...
EngineConfigurationManager.createFromFile(<settings_file_name>).getPrologEngine(getClass());</pre></div>
<h2 id="lowLevelAPI">The Low-Level Querying API</h2>
<p>
This section introduces the JPC low-level API for creating and manipulating Prolog queries.
This API, inspired by the <a href="http://www.swi-prolog.org/packages/jpl/" title="JPL: A bidirectional Prolog/Java interface">JPL</a> library,
provides methods that do not perform automatic conversions between Prolog and Java artifacts.
Instead, a query goal and its results are always expressed by means of Prolog terms.
An alternative to this approach will be presented <a href="#highLevelAPI" title="The high-level querying API">later</a>.
</p>
<p>
In JPC, a Prolog query is reified as a Java class named <a href="/javadocs/org/jpc/query/Query.html" title="Query class">Query</a>.
This class provides methods for executing
<a href="/javadocs/org/jpc/query/Query.html#oneSolutionOrThrow()" title="Query.oneSolutionOrThrow() method">deterministic</a>,
<a href="/javadocs/org/jpc/query/Cursor.html#oneSolution()" title="Cursor.oneSolution() method">semi-deterministic</a> and
<a href="/javadocs/org/jpc/query/Query.html#next()" title="Query.next() method">non-deterministic</a> queries.
A JPC query has three possible <a href="/javadocs/org/jpc/query/CursorState.html" title="CursorState class">states</a>:
<code>READY</code>, <code>OPEN</code> and <code>EXHAUSTED</code>. Figure 2 illustrates the transition between these states by means of a state diagram chart for a JPC query. As shown in the figure, independently of its current state, the <a href="/javadocs/org/jpc/query/Cursor.html#close()" title="Cursor.close() method">close()</a> method always takes it to the <code>READY</code> state. Any attempt to invoke a method that is illegal in the current state raises an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html" title="IllegalStateException class"><code>IllegalStateException</code></a> exception.
</p>
<div class="divImg">
<img src="img/jpc/query_state_diagram.svg" alt="State diagram chart of a JPC query." style="padding-bottom:0.5em;" height="460" />
<div id="imglabel:query_state_diagram" >Fig 2. - State diagram chart of a JPC query.</div>
</div>
<p>
A <a href="/javadocs/org/jpc/query/Solution.html" title="Solution class">query solution</a> is represented as a map binding logic variables to Prolog terms.
Keys of this map are strings representing variable names. Values are terms bound to these logic variables.
</p>
<p>
An an example of the low-level querying API, consider the <a href="/london_underground.html" title="London underground example">London underground case study</a>.
A solution to this problem requires us to provide an implementation for the interfaces
<a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Metro.html" title="The Metro class"><code>Metro</code></a>,
<a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Line.html" title="The Line class"><code>Line</code></a> and
<a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a>.
Since methods in those interfaces frequently need to convert between instances of our <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/package-summary.html" title="Java classes for the London underground case study">Java domain classes</a> and their <a href="/jpc.examples/logtalkdocs/underground_example/" title="Logtalk objects for the London underground case study">Prolog term representation</a>, we implement conversion routines that perform such operations and locate them in the corresponding implementation classes.
The code listing below shows an extract of the implementation of the <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> interface providing such conversion routines.
The <code>asTerm()</code> instance method (lines 17-19) returns the representation, as a Prolog term, of the receiver <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> instance.
The <code>create</code> static method (lines 5-7) returns a new <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> instance from its Prolog term representation.
Equivalent methods are also implemented in other classes in our domain not showed here.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class StationLLApi implements Station {
public static final String STATION_FUNCTOR_NAME = "station";
public static StationLLApi create(Term stationTerm) {
return new StationLLApi(((Atom)stationTerm.arg(1)).getName());
}
private final String name;
private final PrologEngine prologEngine;
public StationLLApi(String name) {
this.name = name;
prologEngine = getPrologEngine(getClass());
}
public Compound asTerm() {
return new Compound(STATION_FUNCTOR_NAME, asList(new Atom(getName())));
}
@Override
public Station connected(Line line) {
String stationVarName = "Station";
Term message = new Compound("connected", asList(new Var(stationVarName), ((LineLLApi)line).asTerm()));
Term goal = new Compound(LogtalkConstants.LOGTALK_OPERATOR, asList(asTerm(), message));
Query query = prologEngine.query(goal);
Term stationTerm = query.oneSolutionOrThrow().get(stationVarName);
return create(stationTerm);
}
... // other methods declared in the Station interface.
}</pre></div>
<p>
The code also shows the implementation of the <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html#connected(org.jpc.examples.metro.model.Line)" title="The Station.connected(Line) method"><code>connected(Line)</code></a> method
declared in the <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> interface.
Line 24 defines a Logtalk message with the form <code>connected(Station, a_line)</code>, where <code>Station</code> is an unbound logic variable and <code>a_line</code> the term representation of the line received as a parameter.
A goal is created in the next line with the form <code>::(this_station, message</code>), where <code>this_station</code> is the term representation of the <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> instance receiving the method call and <code>message</code> the Logtalk message created on line 24.
A query is instantiated in line 26 from this goal.
The binding of the <code>Station</code> Prolog variable corresponding to the first solution is found on line 27, and a new <a href="/jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="The Station class"><code>Station</code></a> instance is created and returned from this term representation on line 28.
</p>
<p>
Next section will set the basis for writing, in a more convenient way, the common conversion operations reviewed in this section.
</p>
<h2 id="conversionAPI">The Conversion API</h2>
<p>
JPC provides an API, inspired by <a href="https://code.google.com/p/google-gson/" title="Google's Gson">Google's Gson</a>, for converting between Java Objects into their Prolog term representation and back.
This conversion API can work with any kind of objects, including those whose source code is not available.
It provides constructs for:
</p>
<div class="divList">
<ul>
<li>Defining (bidirectional) Java-Prolog conversion functions (<a href="#implementingConverters" title="JPC converters">converters</a>).</li>
<li>Inferring the best target type of a conversion operation (<a href="#implementingTypeSolvers" title="JPC type solvers">type solvers</a>).</li>
<li>(Optionally) instantiating conversion target types (<a href="#implementingFactories" title="JPC factories">factories</a>).</li>
</ul>
</div>
<h3 id="conversionContext">The JPC Context</h3>
<p>
The primary JPC class is a conversion context, modelled by the <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> class.
This context encapsulates a bidirectional conversion strategy for a set of Java objects and Prolog terms.
A context is configured in term of converters, type solvers, factories and other conversion artefacts.
Figure 3 illustrates its main components and a typical interaction with a user of the library.
</p>
<div class="divImg">
<img src="img/jpc/jpc_context.svg" alt="The JPC Context." style="padding-bottom:0.5em;" height="190" />
<div id="imglabel:jpc_context" >Fig 3. - The JPC Context.</div>
</div>
<p>
In order to facilitate the configuration of a <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> instance, there is also a <a href="/javadocs/org/jpc/JpcBuilder.html" title="JpcBuilder class"><code>JpcBuilder</code></a> class with a straightforward fluent API for configuring its properties. This configuration involves the registration of custom conversion artefacts (e.g., <a href="#implementingConverters" title="Converters">converters</a>, <a href="#implementingTypeSolvers" title="Type solvers">type solvers</a> and <a href="#implementingFactories" title="Factories">factories</a>).
The example below shows how to configure a builder to create a custom <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> context that knows how to convert objects from the <a href="/london_underground.html" title="London underground example"><code>London underground case study</code></a>.
</p>
<div class="codeEditor"><pre id="metroCustomConverter" data-editor="java" data-show-gutter="true">
public static final Jpc jpc = JpcBuilder.create()
.register(new MetroConverter())
.register(new LineConverter())
.register(new StationConverter()).build();</pre></div>
<p>
Examples of conversions employing this custom JPC context are shown below:
</p>
<div class="codeEditor"><pre id="metroCustomConversions" data-editor="java" data-show-gutter="true">
Term term = new Compound("station", asList(new Atom("central-park"))); //a Prolog term representing the station with name "central-park"
Station station = jpc.fromTerm(term); //a Java object representing the station with name "central-park"
assertEquals(term, jpc.toTerm(station));</pre></div>
<p>
In addition to allowing custom conversions, JPC is bundled with a predefined catalog of converters that support a considerable number of common conversions. This minimises the amount of code to be written when defining new conversions.
</p>
<h3 id="implementingConverters">Implementing Converters</h3>
<p>
JPC provides two interfaces for defining conversions from Java to Prolog (<a href="/javadocs/org/jpc/converter/ToTermConverter.html" title="ToTermConverter class"><code>ToTermConverter</code></a>) and vice versa (<a href="/javadocs/org/jpc/converter/FromTermConverter.html" title="FromTermConverter class"><code>FromTermConverter</code></a>).
The <a href="jpc.examples/javadocs/org/jpc/examples/metro/model/hlapi/converters/StationConverter.html" title="StationConverter class"><code>StationConverter</code></a> class in the code below implements both interfaces. It implements a method defining the conversion of <a href="jpc.examples/javadocs/org/jpc/examples/metro/model/Station.html" title="Station class"><code>Station</code></a> instances to (lines 7-9) and from (lines 11-14) a Prolog compound term.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class StationConverter implements
ToTermConverter<Station, Compound>,
FromTermConverter<Compound, Station> {
public static final String STATION_FUNCTOR = "station";
@Override public Compound toTerm(Station station, Class<Compound> termClass, Jpc context) {
return new Compound(STATION_FUNCTOR, asList(new Atom(station.getName())));
}
@Override public Station fromTerm(Compound term, Type type, Jpc context) {
String stationName = ((Atom)term.arg(1)).getName();
return new Station(stationName);
}
}</pre></div>
<p>
If a converter is unable to perform a conversion operation, it should signal it by means of throwing a <a href="http://jconverter.github.io/javadocs/org/jconverter/converter/ConversionException.html" title="ConversionException class"><code>ConversionException</code></a> exception.
Custom converters can be registered in a JPC context by means of the <a href="http://java-prolog-connectivity.github.io/javadocs/org/jpc/JpcBuilder.html#register(org.jpc.converter.JpcConverter)" title="JpcBuilder.register(JpcConverter) method"><code>JpcBuilder.register(JpcConverter)</code></a> method (and its overloaded variations) in the <a href="/javadocs/org/jpc/JpcBuilder.html" title="JpcBuilder class"><code>JpcBuilder</code></a> class.
</p>
<h3 id="implementingTypeSolvers">Implementing Type Solvers</h3>
<p>
When no type information is provided in a conversion, JPC attempts to infer the best target type based on the actual source object to convert.
For example, a Prolog list term with a certain structure may be reified, by convention, as a map in Java.
Type solvers provide a mechanism for telling JPC what is the best target type in a conversion operation.
The code below shows an extract of a type solver.
Note that it implements the <a href="/javadocs/org/jpc/converter/typeSolver/TypeSolver.html" title="TypeSolver class"><code>TypeSolver</code></a> interface.
In this example, the type solver returns a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" title="Map class"><code>Map</code></a> class on line 13 if it can conclude that the term to convert looks like a map in Java.
If it is unable to assign a conversion type to the term it signals it throwing a <a href="/javadocs/org/jpc/converter/typeSolver/UnrecognizedObjectException.html" title="UnrecognizedObjectException class"><code>UnrecognizedObjectException</code></a> exception (line 15).
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class MapTypeSolver implements TypeSolver<Compound> {
@Override public Type getType(Compound term) {
if(term.isList()) {
ListTerm list = term.asList();
Predicate<Term> isMapEntry = new Predicate<Term>() {
@Override
public boolean apply(Term term) {
return isMapEntry(term);
}
};
if(!list.isEmpty() && Iterables.all(list, isMapEntry))
return Map.class;
}
throw new UnrecognizedObjectException();
}
private boolean isMapEntry(Term term) {
...
}
}</pre></div>
<p>
Custom type solvers can be registered in a JPC context by means of the <a href="http://java-prolog-connectivity.github.io/javadocs/org/jpc/JpcBuilder.html#register(org.jpc.converter.typesolver.TypeSolver)" title="JpcBuilder.register(TypeSolver) method"><code>JpcBuilder.register(TypeSolver)</code></a> method (and its overloaded variations) in the <a href="/javadocs/org/jpc/JpcBuilder.html" title="JpcBuilder class"><code>JpcBuilder</code></a> class.
</p>
<h3 id="implementingFactories">Implementing Factories</h3>
<p>
If a converter does not know how to instantiate a conversion target type (e.g., it is abstract), it can ask the <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> context for an instance of such type.
For instance, in the type solver example above a type solver may identify the type of a Prolog list with a certain structure as a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" title="Map class"><code>Map</code></a>. But the type solver does not provide any mechanism to instantiate such a type, since its only responsibility is to give a hint on the appropriate conversion type.
Assuming that a registered factory can instantiate Java maps, a converter only needs to invoke the <a href="http://jconverter.github.io/javadocs/org/jconverter/JConverter.html#instantiate(java.lang.reflect.Type)" title="JConverter.instantiate(Type) method"><code>instantiate(Type)</code></a> method in a <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> context to obtain an instance of the desired type.
An example of this simple factory is shown below.
Note that it implements the <a href="http://jconverter.github.io/javadocs/org/jconverter/factory/Factory.html" title="Factory class"><code>Factory</code></a> interface.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class MapFactory implements Factory<Map<?,?>>() {
@Override
public Map<?,?> instantiate(Type type) {
return new HashMap<>();
}
}</pre></div>
<p>
If a factory is unable to instantiate a type, it should signal it by means of throwing a <a href="http://jconverter.github.io/javadocs/org/jconverter/factory/FactoryException.html" title="FactoryException class"><code>FactoryException</code></a> exception.
Custom factories can be registered in a JPC context by means of the <a href="http://jconverter.github.io/javadocs/org/jconverter/JConverterBuilder.html#register(org.jconverter.factory.Factory)" title="JConverterBuilder.register(Factory) method"><code>JpcBuilder.register(Factory)</code></a> method in the <a href="/javadocs/org/jpc/JpcBuilder.html" title="JpcBuilder class"><code>JpcBuilder</code></a> class.
</p>
<h3 id="primitivesConversions">Primitives Conversions</h3>
<p>
In this section we illustrate how to convert between Java and Prolog primitives. In order to facilitate the discussion, we also include in this section conversions of the Java <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html" title="String class"><code>String</code></a> class, since it is the natural equivalent of the <a href="/javadocs/org/jpc/term/Atom.html" title="Atom class"><code>Atom</code></a> primitive Prolog type.
</p>
<p>
The simplest way to use our library is by means of the <a href="/javadocs/org/jpc/Jpc.html#toTerm(java.lang.Object)" title="Jpc.toTerm(Term) method"><code>toTerm(Term)</code></a> and <a href="/javadocs/org/jpc/Jpc.html#fromTerm(org.jpc.term.Term)" title="Jpc.fromTerm(Term) method"><code>fromTerm(Term)</code></a> methods in the <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> class <a href="#implementingConverters" title="Conversion methods">introduced before</a>.
Below there is a list of successful assertions that illustrates some pre-defined conversions of Java types to Prolog terms.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
assertEquals(new Atom("true"), jpc.toTerm(true)); //Boolean to Atom
assertEquals(new Atom("c"), jpc.toTerm('c')); //Character to Atom
assertEquals(new Atom("1"), jpc.toTerm("1")); //String to Atom
assertEquals(new IntegerTerm(1), jpc.toTerm(1)); //Integer to IntegerTerm
assertEquals(new FloatTerm(1), jpc.toTerm(1D)); //Double to FloatTerm</pre></div>
<p>
Pre-defined conversions of Prolog terms to Java types are shown below.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
assertEquals(true, jpc.fromTerm(new Atom("true"))); //Atom to Boolean
assertEquals("c", jpc.fromTerm(new Atom("c"))); //Atom to String
assertEquals("1", jpc.fromTerm(new Atom("1"))); //Atom to String
assertEquals(1L, jpc.fromTerm(new IntegerTerm(1))); //IntegerTerm to Long
assertEquals(1D, jpc.fromTerm(new FloatTerm(1))); //FloatTerm to Double</pre></div>
<h3 id="typedConversions">Typed Conversions</h3>
<p>
The <a href="/javadocs/org/jpc/Jpc.html" title="Jpc class"><code>Jpc</code></a> class conversion methods can receive as a second parameter the expected type of the converted object.
Some examples of Java-Prolog conversions that specify the expected Prolog term type are shown below.
In line 1, the <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html" title="Integer class"><code>Integer</code></a> 1 is converted to an <a href="/javadocs/org/jpc/term/Atom.html" title="Atom class"><code>Atom</code></a> instead of an <a href="/javadocs/org/jpc/term/IntegerTerm.html" title="IntegerTerm class"><code>IntegerTerm</code></a>. This is because we specify the <a href="/javadocs/org/jpc/term/Atom.html" title="Atom class"><code>Atom</code></a> class as the target conversion type.
In line 2, the string <code>"1"</code> is converted to an <a href="/javadocs/org/jpc/term/IntegerTerm.html" title="IntegerTerm class"><code>IntegerTerm</code></a>.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">assertEquals(new Atom("1"), jpc.toTerm(1, Atom.class)); //Integer to Atom
assertEquals(new IntegerTerm(1), jpc.toTerm("1", IntegerTerm.class)); //String to IntegerTerm</pre></div>
<p>
Below there are examples of Prolog-Java conversions that specify the expected Java type.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
assertEquals(1, jpc.fromTerm(new Atom("1"), Integer.class)); //Atom to Integer
assertEquals("1", jpc.fromTerm(new IntegerTerm(1), String.class)); //IntegerTerm to String
assertEquals("true", jpc.fromTerm(new Atom("true"), String.class)); //Atom to String
assertEquals('c', jpc.fromTerm(new Atom("c"), Character.class)); //Atom to Character</pre></div>
<h3 id="multiValuedConversions">Multi-Valued Conversions</h3>
<p>
The default Jpc catalog of converters also provides conversions for multi-valued data types such as arrays, collections, and maps. Below there is an example showing a conversion of an array object with a string and an integer element: <code>{"apple", 10}</code>.
Its result is a Prolog term list having as elements an atom and an integer term: <code>[apple, 10]</code>.
Alternatively, we could have used a list instead of an array. For example, we would have obtained exactly the same result by replacing line 1 by:
<code>Term term = jpc.toTerm(asList("apple", 10));</code>
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
Term term = jpc.toTerm(new Object[]{"apple", 10});
assertEquals(
new Compound(".", asList(new Atom("apple"), // equivalent to .(apple, .(10, []))
new Compound(".", asList(new IntegerTerm(10),
new Atom("[]"))))),
term);</pre></div>
<p>
A slightly more complex example is illustrated below. First, a Java map is instantiated (lines 1-4).
The default term conversion is applied on line 5, generating a Prolog list with two key-value pairs: <code>[apple:10, orange:20]</code>. This result is tested on lines 7-8.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
Map<String, Integer> map = new LinkedHashMap<String, Integer>() {{ // LinkedHashMap preserves insertion order
put("apple", 10);
put("orange", 20);
}};
Term term = jpc.toTerm(map);
List<Term> listTerm = term.asList(); // converts a Prolog list term to a list of terms
assertEquals(new Compound(":", asList(new Atom("apple"), new IntegerTerm(10))), listTerm.get(0));
assertEquals(new Compound(":", asList(new Atom("orange"), new IntegerTerm(20))), listTerm.get(1));</pre></div>
<h3 id="genericTypesSupport">Generic Types Support</h3>
<p>
JPC provides extensive support for generic types.
Consider the example below.
A Prolog list term is created on line 1. We use the <a href="https://code.google.com/p/guava-libraries/wiki/ReflectionExplained" title="TypeToken class"><code>TypeToken</code></a> class (from Google's <a href="https://code.google.com/p/guava-libraries/" title="Google's Guava library"><code>Guava library</code></a>) to obtain an instance of the parameterised type <code>List<String></code> (line 2).
Then we give this type as a hint to the converter (line 3) and we verify on lines 4 and 5 that the elements of the Java <a href="http://docs.oracle.com/javase/7/docs/api/java/util/List.html" title="List class"><code>List</code></a>
are indeed instances of <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html" title="String class"><code>String</code></a>, as it was specified on line 3.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
Term listTerm = listTerm(new Atom("1"), new Atom("2")); // creates a list term from a list of terms
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = jpc.fromTerm(listTerm, type);
assertEquals("1", list.get(0));
assertEquals("2", list.get(1));</pre></div>
<p>
In the previous example, the type passed to the converter was redundant, since elements in the Prolog list are atoms, which are converted by default to <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html" title="String class"><code>String</code></a> instances in Java.
Consider, however, the example below. The main change w.r.t. the previous example is that the type we send as a hint is now <code>List<Integer></code> (line 3).
This instructs the converter to instantiate a list where all its elements are integers, as demonstrated on lines 4 and 5.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">Term listTerm = listTerm(new Atom("1"), new Atom("2"));
Type type = new TypeToken<List<Integer>>(){}.getType();
List<Integer> list = jpc.fromTerm(listTerm, type);
assertEquals(1, list.get(0));
assertEquals(2, list.get(1));</pre></div>
<h3 id="typeInferenceExample">Inference of Conversion Target Types</h3>
<p>
A <a href="#implementingTypeSolvers" title="Implementing type solvers"><code>previous example</code></a> showed the implementation of a type solver responsible of determining if the best conversion type of a Prolog term is a Java <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" title="Map class"><code>Map</code></a>.
Below we show a conversion example that relies on such type solver.
Note that this type solver is part of the default JPC type solvers catalog, so it does not have to be explicitly registered in a default conversion context.
On line 3 we create a list term from two previously created compound terms.
We convert it to a Java map on line 4 and test its values on lines 5 and 6.
As expected, our library infers that the best Java type of the term should be a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" title="Map class"><code>Map</code></a>.
This is because the type solver finds that all the elements in the Prolog list (<code>[apple:10, orange:20]</code>) are compounds with an arity of 2 and with functor <code>':'</code>, which are mapped by default to map entries (i.e., instances of the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html" title="Map.Entry class"><code>Map.Entry</code></a> class).
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
Compound c1 = new Compound(":", asList(new Atom("apple"), new IntegerTerm(10)));
Compound c2 = new Compound(":", asList(new Atom("orange"), new IntegerTerm(20)));
Term listTerm = listTerm(c1, c2);
Map map = jpc.fromTerm(listTerm);
assertEquals(10L, map.get("apple"));
assertEquals(20L, map.get("orange"));</pre></div>
<p>
Alternatively, line 4 could be replaced by <code>List list = jpc.fromTerm(listTerm, List.class);</code> The type hint <code>List.class</code> given by the programmer has higher priority that the one inferred by the type solver.
In this case, the result would therefore be a list of map entries since the Prolog list would be converted to a Java list (i.e., an instance of a class implementing <a href="http://docs.oracle.com/javase/7/docs/api/java/util/List.html" title="List class"><code>List</code></a>), but the default conversion of each term in the list (a compound with arity 2 and functor <code>':'</code>) would still be a map entry object.
</p>
<p>
Note that JPC leaves to the programmer the responsibility of providing enough information (i.e., a target type) in case where ambiguities are possible.
<!--
For example, the previous type solver may answer false negatives if it cannot conclude something from the structure of members in the list (i.e., the list term is empty).
If the programmer always specify the intended conversion type the possible ambiguity disappears.
-->
</p>
<h3 id="termQuantifiedConverterExample">Term-Quantified Converters</h3>
<p>
A JPC context can associate converters to arbitrary Prolog terms.
This provides a convenient mechanism for limiting the application scope of converters.
This is better explained with an example.
Consider the following <code>HelloConverter</code> that knows how to converter from compounds to the string "<Greeting> <Name>"; where <Greeting> is the name of the compound and <Name> its first argument.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
class HelloConverter implements FromTermConverter<Compound, String> {
@Override public String fromTerm(Compound term, Type targetType, Jpc context) {
return ((Atom)term.getName()).getName() + " " + ((Atom)term.arg(1)).getName();
}
}</pre></div>
<p>
If we would like to restrict this converter to be applied only to terms subsumed by the term <code>hello(_)</code>, we could write:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
JpcBuilder builder = JpcBuilder.create();
Compound helloCompound = new Compound("hello", asList(Var.ANONYMOUS_VAR));
builder.register(new HelloConverter(), helloCompound);
Jpc jpc = builder.build();</pre></div>
<p>
Below a usage example of this custom conversion context:
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
Compound helloWorldCompound = new Compound("hello", asList(new Atom("world")));
assertEquals("hello world", jpc.fromTerm(helloWorldCompound));</pre></div>
<h2 id="highLevelAPI">The High-Level Querying API</h2>
<p>
JPC provides features that abstract programmers from explicit conversions from and to Prolog terms.
Below an example of an alternative implementation of the <code>Station</code> interface that makes use of such high-level API.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class StationHLApi implements Station {
public static final String STATION_FUNCTOR_NAME = "station";
private final String name;
private final PrologEngine prologEngine;
public StationHLApi(String name) {
this.name = name;
prologEngine = getPrologEngine(getClass());
}
@Override
public Station connected(Line line) {
String stationVarName = "Station";
Term message = jpc.compound("connected", asList(new Var(stationVarName), line));
Term objectMessage = jpc.compound("::", asList(this, message));
Query query = getPrologEngine().query(objectMessage, jpc);
return query.<Station>selectObject(stationVarName).oneSolution();
}
@Override
public List<Station> nearby() {
String stationVarName = "Station";
Term message = new Compound("nearby", asList(new Var(stationVarName)));
Term objectMessage = jpc.compound("::", asList(this, message));
Query query = getPrologEngine().query(objectMessage, jpc);
return query.<Station>selectObject(stationVarName).allSolutions();
}
... // other methods declared in the Station interface.
}</pre></div>
<p>
In the previous implementation, we assume a custom Jpc context that knows how to convert between instances of <code>Station</code> and Prolog terms.
By means of this context, the code of the class is not polluted with explicit inter-language conversion operations.
For example, on line 19 the expression <code>query.<Station>selectObject(stationVarName).oneSolution()</code> returns the transformation to a Java object of the term that has been bound to the logic variable <code>stationVarName</code> in the first solution to the query.
Similarly, on line 28 the operation of gathering all the solutions to the query and transforming them to a Java list of stations is accomplished in just one line of code.
</p>
<!--
<a href="#conversionContext" title="List class"><code>List</code></a>
<p>
The previous examples employed only predefined converters.
Assuming the custom conversion context defined <a href="#metroCustomConverter" title="Undeground example custom converter"><code>before</code></a>, we revisit the \lstinline{Station} class shown in listing \ref{lst:stationJpl}.
Listing \ref{lst:stationJpc} shows a new implementation of such class.
Using our library, the \lstinline{connected(Line)} method was reduced from 14 to 7 lines of code.
In addition, the methods \lstinline{asTerm()} and \lstinline{create(Term)} are not in the \lstinline{Station} class anymore since they have been encapsulated into a converter class.
Note that terms are easily created according to a conversion context. In line 5, the last argument of the compound is an instance of \lstinline{Line}. The conversion of this object to a term is done automatically by our framework. Conversely, in listing \ref{lst:stationJpl} (line 17), we were forced to invoke an explicit conversion when we requested the term representation of the line object.
The same applies in line 6, where the \lstinline{Station} instance denoted by the \lstinline{this} keyword is automatically transformed to its term representation.
</p>
<p>
A \lstinline{Query} object is instantiated on line 7 from an object abstracting a Prolog engine. %(as briefly discussed in section \ref{architecture}).
Note that this object may (optionally) receive a context.
The advantage of making a query instance aware of a conversion context becomes clear on line 8.
To better understand this, recall from section \ref{prologVMAbstraction} that a Prolog solution is represented as a map binding variable names to terms. On line 8, the invocation of the \lstinline{selectObject(String)} method encapsulates the original query in an adapter, where each solution of this query adapter is an object whose term representation is given in the argument of \lstinline{selectObject}, taking into account the bindings of any variables in the solution.
In our example, the solution object is expressed as the Prolog variable \lstinline{Station}, which has been bound to a term representing an instance of \lstinline{Station}. The conversion of this term to a \lstinline{Station} object is transparently accomplished by our library.
</p>
<div class="codeEditor"><pre data-editor="java" data-show-gutter="true">
public class Station {
...
public Station connected(Line line) {
String stationVarName = "Station";
Term message = jpcContext.compound("connected", asList(new Var(stationVarName), line));
Term objectMessage = jpcContext.compound("::", asList(this, message));
Query query = getPrologEngine().query(objectMessage, jpcContext);
return query.<Station>selectObject(stationVarName).oneSolution();
}
}</pre></div>
<p>
The previous example makes use of a deterministic query. % by means of the \lstinline{oneSolution()} method.
The \lstinline{Query} class (and query adapters) interface also supports non-deterministic queries (i.e., backtracking over solutions).
Internally, this relies on the concrete implementation of the chosen JPC driver. As already mentioned in section \ref{prologVMAbstraction}, this discussion has been left out of the scope of this work.
</p>
-->
<!--
<h2>Exception Handling</h2>
-->
<!--
<h2>Reference Management</h2>
-->
<h2>Other Features</h2>
<p>
There are several other JPC's features that have not been discussed here. Some examples are related to inter-language exception handling, preservation of object identity in conversions, and the Prolog-side JPC's API.
These and other features will be discussed in a future version of this tutorial.
</p>
</div> <!-- end of content -->
</body>
</html>