it.cnr.istc.pst.cognition.koala.reasoner.owl.jena.OWLKoalaObservationReasoner   A
last analyzed

Complexity

Total Complexity 28

Size/Duplication

Total Lines 591
Duplicated Lines 5.58 %

Importance

Changes 0
Metric Value
eloc 333
dl 33
loc 591
c 0
b 0
f 0
rs 10
wmc 28

6 Methods

Rating   Name   Duplication   Size   Complexity  
F doHandleObservation(String,Object,String) 0 405 16
A close() 0 6 2
B doPrepareObservationNotifications() 0 89 6
A OWLKoalaObservationReasoner(String,String) 0 8 1
A getModel() 0 4 1
A doInitialize(EnvironmentReasoner) 33 33 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
package it.cnr.istc.pst.cognition.koala.reasoner.owl.jena;
2
3
import java.io.BufferedWriter;
4
import java.io.File;
5
import java.io.FileWriter;
6
import java.io.IOException;
7
import java.io.PrintWriter;
8
import java.util.ArrayList;
9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
12
13
import org.apache.jena.rdf.model.Property;
14
import org.apache.jena.rdf.model.Resource;
15
import org.apache.jena.rdf.model.Statement;
16
17
import it.cnr.istc.pst.cognition.koala.lang.dictionary.KoalaPropertyDictionary;
18
import it.cnr.istc.pst.cognition.koala.reasoner.environment.EnvironmentReasoner;
19
import it.cnr.istc.pst.cognition.koala.reasoner.observation.ObservationReasoner;
20
import it.cnr.istc.pst.cognition.koala.reasoner.observation.ObservationReasonerUpdate;
21
22
/**
23
 * 
24
 * @author anacleto
25
 *
26
 */
27
public class OWLKoalaObservationReasoner extends ObservationReasoner
28
{
29
	private OWLKoalaModel kb;											// the knowledge-base
30
	private Map<Statement, ObservationReasonerUpdate> cache;		// cache of notified observations
31
	
32
	private long inferenceTime;										// count time spent doing inference
33
	private int inferenceCounter;									// count number of inferred events
34
	private PrintWriter writer;
35
	
36
	/**
37
	 * 
38
	 * @param ontologyFilePath
39
	 * @param ruleFilePath
40
	 */
41
	public OWLKoalaObservationReasoner(String ontologyFilePath, String ruleFilePath) {
42
		super();
43
		// create a knowledge-base instance
44
		this.kb = new OWLKoalaModel(ontologyFilePath, ruleFilePath);
45
		// setup cache
46
		this.cache = new HashMap<Statement, ObservationReasonerUpdate>();
47
		this.writer = null;
48
		this.inferenceTime = 0;
49
	}
50
	
51
	/**
52
	 * 
53
	 */
54 View Code Duplication
	@Override
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
55
	protected void doInitialize(EnvironmentReasoner env) 
56
	{
57
		// set parameters
58
		this.inferenceTime = 0;
59
		this.inferenceCounter = 0;
60
		// current time
61
		long now = System.currentTimeMillis();
62
		// setup model
63
		this.kb.setup(env.getModel());
64
		// time
65
		long time = System.currentTimeMillis() - now;
66
		// update inference time
67
		this.inferenceTime += time;
68
		
69
		// setup cache
70
		this.cache.clear();
71
		
72
		try
73
		{
74
			// create data file
75
			File dataFile = new File("data/observation_reasoner_" + System.currentTimeMillis() + ".csv");
76
			// create file and write the header of the CSV
77
			this.writer = new PrintWriter(new BufferedWriter(new FileWriter(dataFile)));
78
			// print header
79
			this.writer.print("timestamp;number of inferred events;total inference time\n");
80
			this.writer.flush();
81
		}
82
		catch (IOException ex) {
83
			// set to null writer
84
			this.writer = null;
85
			// print error message 
86
			System.err.println("[ObservationReasoner] Error opening writer buffer for data\n- message: " + ex.getMessage());
87
		}
88
	}
89
	
90
	/**
91
	 * 
92
	 * @return
93
	 */
94
	@Override
95
	public OWLKoalaModel getModel() {
96
		// get current knowledge base
97
		return this.kb;
98
	}
99
	
100
	/**
101
	 * 
102
	 * @param sensorId
103
	 * @param observationValue
104
	 * @param propertyUri
105
	 * @throws Exception
106
	 */
107
	@Override
108
	public void doHandleObservation(String sensorId, Object observationValue, String propertyUri) 
109
			throws Exception
110
	{
111
		// get current time
112
		long now = System.currentTimeMillis();
113
		try
114
		{
115
			// retrieve sensor individual according to the ID
116
			Resource sensor = this.kb.getResourceById(new Long(sensorId));
117
			// create observation individual
118
			Resource observation = this.kb.createIndividual(OWLKoalaNameSpace.SSN.getNs() + "Observation");
119
			// create sensor output individual
120
			Resource output = this.kb.createIndividual(OWLKoalaNameSpace.SSN.getNs() + "SensorOutput");
121
			
122
			// assert properties
123
			this.kb.assertProperty(observation.getURI(), OWLKoalaNameSpace.SSN.getNs() + "hasOutput", output.getURI());
124
			this.kb.assertProperty(observation.getURI(), OWLKoalaNameSpace.SSN.getNs() + "observedBy", sensor.getURI());
125
			
126
			// check property in order to create observation value accordingly
127
			switch (KoalaPropertyDictionary.getPropertyByURI(propertyUri))
128
			{
129
				case KOALA_LUMINOSITY : 
130
				{	
131
					// assert observation property
132
					this.kb.assertProperty(
133
							observation.getURI(), 
134
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty",
135
							OWLKoalaNameSpace.KOALA.getNs() + "Luminosity");
136
					
137
					
138
					// create observation value 
139
					Resource value = this.kb.createIndividual(
140
							OWLKoalaNameSpace.KOALA.getNs() + "LuminosityObservationValue");
141
				
142
					// assert data property
143
					this.kb.assertDataProperty(
144
							value.getURI(), 
145
							OWLKoalaNameSpace.KOALA.getNs() + "hasLuminosityValue",
146
							(Double) observationValue);
147
					
148
					// assert property
149
					this.kb.assertProperty(
150
							output.getURI(), 
151
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
152
							value.getURI());
153
				}
154
				break;
155
	
156
				case KOALA_TEMPERATURE : 
157
				{
158
					// assert observation property
159
					this.kb.assertProperty(
160
							observation.getURI(), 
161
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
162
							OWLKoalaNameSpace.KOALA.getNs() + "Temperature");
163
					
164
					
165
					// create observation value 
166
					Resource value = this.kb.createIndividual(
167
							OWLKoalaNameSpace.KOALA.getNs() + "TemperatureObservationValue");
168
				
169
					// assert data property
170
					this.kb.assertDataProperty(
171
							value.getURI(), 
172
							OWLKoalaNameSpace.KOALA.getNs() + "hasTemperatureValue", 
173
							(Double) observationValue);
174
					
175
					// assert property
176
					this.kb.assertProperty(
177
							output.getURI(), 
178
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
179
							value.getURI());
180
				}
181
				break;
182
				
183
				
184
				case KOALA_ENERGY : 
185
				{
186
					// assert observation property
187
					this.kb.assertProperty(
188
							observation.getURI(), 
189
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
190
							OWLKoalaNameSpace.KOALA.getNs() + "Energy");
191
					
192
					
193
					// create observation value 
194
					Resource value = this.kb.createIndividual(
195
							OWLKoalaNameSpace.KOALA.getNs() + "EnergyObservationValue");
196
				
197
					// assert data property
198
					this.kb.assertDataProperty(
199
							value.getURI(), 
200
							OWLKoalaNameSpace.KOALA.getNs() + "hasEnergyValue",
201
							(Double) observationValue);
202
					
203
					// assert property
204
					this.kb.assertProperty(
205
							output.getURI(), 
206
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
207
							value.getURI());
208
				}
209
				break;
210
					
211
				case KOALA_PRESENCE : 
212
				{
213
					// assert observation property
214
					this.kb.assertProperty(
215
							observation.getURI(), 
216
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
217
							OWLKoalaNameSpace.KOALA.getNs() + "Presence");
218
					
219
					
220
					// create observation value 
221
					Resource value = this.kb.createIndividual(
222
							OWLKoalaNameSpace.KOALA.getNs() + "PresenceObservationValue");
223
				
224
					// assert data property
225
					this.kb.assertDataProperty(
226
							value.getURI(), 
227
							OWLKoalaNameSpace.KOALA.getNs() + "hasPresenceValue",
228
							(Boolean) observationValue);
229
					
230
					// assert property
231
					this.kb.assertProperty(
232
							output.getURI(), 
233
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
234
							value.getURI());
235
					
236
				} 
237
				break;
238
				
239
				case KOALA_BATTERY_LEVEL: 
240
				{
241
					// assert observation property
242
					this.kb.assertProperty(
243
							observation.getURI(), 
244
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
245
							OWLKoalaNameSpace.KOALA.getNs() + "BatteryLevel");
246
					
247
					
248
					// create observation value 
249
					Resource value = this.kb.createIndividual(
250
							OWLKoalaNameSpace.KOALA.getNs() + "BatteryLevelObservationValue");
251
				
252
					// assert data property
253
					this.kb.assertDataProperty(
254
							value.getURI(), 
255
							OWLKoalaNameSpace.KOALA.getNs() + "hasBatteryLevelValue",
256
							(Double) observationValue);
257
					
258
					// assert property
259
					this.kb.assertProperty(
260
							output.getURI(), 
261
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
262
							value.getURI());
263
				}
264
				break;
265
				
266
				
267
				case KOALA_BLOOD_PRESSURE : 
268
				{
269
					// get observed ranges
270
					Integer[] ranges = (Integer[]) observationValue;
271
					int min = ranges[0];
272
					int max = ranges[1];
273
					
274
					// assert observation property
275
					this.kb.assertProperty(
276
							observation.getURI(), 
277
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
278
							OWLKoalaNameSpace.KOALA.getNs() + "BloodPressure");
279
					
280
					
281
					// create observation value 
282
					Resource value = this.kb.createIndividual(
283
							OWLKoalaNameSpace.KOALA.getNs() + "BloodPressureObservationValue");
284
				
285
					// assert data property
286
					this.kb.assertDataProperty(
287
							value.getURI(), 
288
							OWLKoalaNameSpace.KOALA.getNs() + "hasMinBloodPressureValue",
289
							min);
290
					
291
					this.kb.assertDataProperty(
292
							value.getURI(), 
293
							OWLKoalaNameSpace.KOALA.getNs() + "hasMaxBloodPressureValue",
294
							max);
295
					
296
					// assert property
297
					this.kb.assertProperty(
298
							output.getURI(), 
299
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
300
							value.getURI());
301
				}
302
				break;
303
				
304
				
305
				case KOALA_BLOOD_SUGAR : 
306
				{
307
					// assert observation property
308
					this.kb.assertProperty(
309
							observation.getURI(), 
310
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
311
							OWLKoalaNameSpace.KOALA.getNs() + "BloodSugar");
312
					
313
					
314
					// create observation value 
315
					Resource value = this.kb.createIndividual(
316
							OWLKoalaNameSpace.KOALA.getNs() + "BloodSugarObservationValue");
317
				
318
					// assert data property
319
					this.kb.assertDataProperty(
320
							value.getURI(), 
321
							OWLKoalaNameSpace.KOALA.getNs() + "hasBloodSugarValue",
322
							(Double) observationValue);
323
					
324
					// assert property
325
					this.kb.assertProperty(
326
							output.getURI(), 
327
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
328
							value.getURI());
329
				}
330
				break;
331
				
332
				case KOALA_BODY_TEMPERATURE : 
333
				{
334
					// assert observation property
335
					this.kb.assertProperty(
336
							observation.getURI(), 
337
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
338
							OWLKoalaNameSpace.KOALA.getNs() + "BodyTemperature");
339
					
340
					
341
					// create observation value 
342
					Resource value = this.kb.createIndividual(
343
							OWLKoalaNameSpace.KOALA.getNs() + "BodyTemperatureObservationValue");
344
				
345
					// assert data property
346
					this.kb.assertDataProperty(
347
							value.getURI(), 
348
							OWLKoalaNameSpace.KOALA.getNs() + "hasBodyTemperatureValue",
349
							(Double) observationValue);
350
					
351
					// assert property
352
					this.kb.assertProperty(
353
							output.getURI(), 
354
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
355
							value.getURI());
356
				}
357
				break;
358
				
359
				
360
				case KOALA_BODY_WEIGHT : 
361
				{
362
					// assert observation property
363
					this.kb.assertProperty(
364
							observation.getURI(), 
365
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
366
							OWLKoalaNameSpace.KOALA.getNs() + "BodyWeight");
367
					
368
					
369
					// create observation value 
370
					Resource value = this.kb.createIndividual(
371
							OWLKoalaNameSpace.KOALA.getNs() + "BodyWeightObservationValue");
372
				
373
					// assert data property
374
					this.kb.assertDataProperty(
375
							value.getURI(), 
376
							OWLKoalaNameSpace.KOALA.getNs() + "hasBodyWeightValue",
377
							(Double) observationValue);
378
					
379
					// assert property
380
					this.kb.assertProperty(
381
							output.getURI(), 
382
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
383
							value.getURI());
384
				}
385
				break;
386
				
387
				
388
				case KOALA_CONTACT : 
389
				{
390
					// assert observation property
391
					this.kb.assertProperty(
392
							observation.getURI(), 
393
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
394
							OWLKoalaNameSpace.KOALA.getNs() + "Contact");
395
					
396
					
397
					// create observation value 
398
					Resource value = this.kb.createIndividual(
399
							OWLKoalaNameSpace.KOALA.getNs() + "ContactObservationValue");
400
				
401
					// assert data property
402
					this.kb.assertDataProperty(
403
							value.getURI(), 
404
							OWLKoalaNameSpace.KOALA.getNs() + "hasContactValue",
405
							(Boolean) observationValue);
406
					
407
					// assert property
408
					this.kb.assertProperty(
409
							output.getURI(), 
410
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
411
							value.getURI());
412
				}
413
				break;
414
				
415
				
416
				case KOALA_HEART_RATE : 
417
				{
418
					// assert observation property
419
					this.kb.assertProperty(
420
							observation.getURI(), 
421
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
422
							OWLKoalaNameSpace.KOALA.getNs() + "HeartRate");
423
					
424
					
425
					// create observation value 
426
					Resource value = this.kb.createIndividual(
427
							OWLKoalaNameSpace.KOALA.getNs() + "HeartRateObservationValue");
428
				
429
					// assert data property
430
					this.kb.assertDataProperty(
431
							value.getURI(), 
432
							OWLKoalaNameSpace.KOALA.getNs() + "hasHeartRateValue",
433
							(Double) observationValue);
434
					
435
					// assert property
436
					this.kb.assertProperty(
437
							output.getURI(), 
438
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
439
							value.getURI());
440
				}
441
				break;
442
				
443
				
444
				case KOALA_OXIMETRY : 
445
				{
446
					// assert observation property
447
					this.kb.assertProperty(
448
							observation.getURI(), 
449
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
450
							OWLKoalaNameSpace.KOALA.getNs() + "Oximetry");
451
					
452
					
453
					// create observation value 
454
					Resource value = this.kb.createIndividual(
455
							OWLKoalaNameSpace.KOALA.getNs() + "OximetryObservationValue");
456
				
457
					// assert data property
458
					this.kb.assertDataProperty(
459
							value.getURI(), 
460
							OWLKoalaNameSpace.KOALA.getNs() + "hasOximetryValue",
461
							(Double) observationValue);
462
					
463
					// assert property
464
					this.kb.assertProperty(
465
							output.getURI(), 
466
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
467
							value.getURI());
468
				}
469
				break;
470
				
471
				case KOALA_VOICE_COMMAND : 
472
				{
473
					// assert observation property
474
					this.kb.assertProperty(
475
							observation.getURI(), 
476
							OWLKoalaNameSpace.SSN.getNs() + "observedProperty", 
477
							OWLKoalaNameSpace.KOALA.getNs() + "VoiceCommand");
478
					
479
					
480
					// create observation value 
481
					Resource value = this.kb.createIndividual(
482
							OWLKoalaNameSpace.KOALA.getNs() + "VoiceCommandObservationValue");
483
				
484
					// assert data property
485
					this.kb.assertDataProperty(
486
							value.getURI(), 
487
							OWLKoalaNameSpace.KOALA.getNs() + "hasVoiceCommandValue",
488
							(String) observationValue);
489
					
490
					// assert property
491
					this.kb.assertProperty(
492
							output.getURI(), 
493
							OWLKoalaNameSpace.SSN.getNs() + "hasValue", 
494
							value.getURI());
495
				}
496
				break;
497
				
498
				
499
				default : 
500
					throw new RuntimeException("[ObservationReasoner] Unknown KOaLa property \"" + propertyUri + "\"");
0 ignored issues
show
Best Practice introduced by
Dedicated exceptions should be preferred over throwing the generic Exception.
Loading history...
501
			}
502
		}
503
		catch (Exception ex) {
504
			// forward exception
505
			throw new Exception(ex.getMessage());
0 ignored issues
show
Best Practice introduced by
Dedicated exceptions should be preferred over throwing the generic Exception.
Loading history...
506
		}
507
		finally {
508
			// compute inference time 
509
			long time = System.currentTimeMillis() - now;
510
			// update total inference time
511
			this.inferenceTime += time;
512
		}
513
	}
514
515
	/**
516
	 * 
517
	 */
518
	@Override
519
	protected List<ObservationReasonerUpdate> doPrepareObservationNotifications() 
520
	{
521
		// get current time
522
		long timestamp = System.currentTimeMillis();
523
		// list of observation to notify 
524
		List<ObservationReasonerUpdate> updates = new ArrayList<ObservationReasonerUpdate>();
525
		try
526
		{
527
			// get the list of inferred events
528
			List<Statement> list = this.kb.getStatements(
529
					OWLKoalaNameSpace.SSN.getNs() + "isProxyFor");
530
			
531
			// check inferred events
532
			for (Statement s : list) 
533
			{
534
				// check if already notified
535
				if (!this.cache.containsKey(s))
536
				{
537
					// increase inference counter
538
					this.inferenceCounter++;
539
					
540
					// get statement elements
541
					Resource subject = s.getSubject();
542
					// get statement's object
543
					Resource object = s.getResource();
544
					
545
					
546
					// get type property
547
					Property pType = this.kb.getProperty(OWLKoalaNameSpace.RDF.getNs() + "type");
548
					// get event property statement
549
					Statement pStatement = subject.getProperty(pType);
550
					// get inferred event type
551
					Resource eventType = pStatement.getResource();
552
					// get the observable feature associated
553
					Property concerns = this.kb.getProperty(OWLKoalaNameSpace.KOALA.getNs()+ "concerns");
554
					// get concerns property statement
555
					Statement cStatement = subject.getProperty(concerns);
556
					// get observable feature
557
					Resource concernedElement = cStatement.getResource();
558
					
559
					// check category
560
					if (object.getURI().equals(OWLKoalaNameSpace.KOALA.getNs() + "ObservedActivity")) 
561
					{
562
						// create activity update
563
						ObservationReasonerUpdate update = this.createActivityUpdate(
564
								subject.getId().getBlankNodeId().getLabelString(), 
565
								eventType.getURI(),
566
								concernedElement.getURI());
567
						
568
						// add update to the list 
569
						updates.add(update);
570
						// add event to the cache
571
						this.cache.put(s, update);
572
					}
573
					else 
574
					{
575
						// create event update
576
						ObservationReasonerUpdate update = this.createEventUpdate(
577
								subject.getId().getBlankNodeId().getLabelString(), 
578
								eventType.getURI(),
579
								concernedElement.getURI());
580
						
581
						// add update to the list
582
						updates.add(update);
583
						// add event to the cache
584
						this.cache.put(s, update);
585
					}
586
				}
587
			}
588
		}
589
		catch (Exception ex) {
590
			System.err.println("[ObservationReasoner] Error while checking inferred events/activities:\n"
591
					+ "\t- message= " + ex.getMessage() + "\n");
592
		}
593
		finally 
594
		{
595
			// write data
596
			if (this.writer != null) 
597
			{
598
				// print inferred event type and service type
599
				this.writer.print(timestamp + ";" + this.inferenceCounter + ";" + this.inferenceTime + "\n");
600
				// write record
601
				this.writer.flush();
602
			}
603
		}
604
		
605
		// get the list of updates
606
		return updates;
607
	}
608
609
	/**
610
	 * 
611
	 */
612
	@Override
613
	public void close() 
614
	{
615
		// close writer
616
		if (this.writer != null) {
617
			this.writer.close();
618
		}
619
	}
620
}