How to set a label to a resource with jena - jena

In my ontology I'm using SKOS concepts. In the documentation there are labels (like prefLabel, etc., mentioned): http://www.w3.org/TR/skos-reference/#labels.
How can I set such a label to a resource in Jena with defining the language?
My example to add a concept looks like this:
Resource skosConcept = infModel.createResource("http://www.w3.org/2004/02/skos/core#Concept");
Resource instance = infModel.createResource("http://eg.com#Instance");
infModel.add(instance, RDF.type, skosConcept);
But how can I define, for example, the skos:prefLabel? With a property to my instance resource? And how to set the language? The class OntResource seems to have such a property for adding a label with language . But I'm using an InfModel so I can't get the resource as an OntResource.

Just like you created the resource with createResource, you can create properties with createProperty, and then add the desired triple to the model in the same way that you already used. The literal with a language type can be created with createLiteral.
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.ReasonerRegistry;
import com.hp.hpl.jena.vocabulary.RDF;
public class SKOS {
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
InfModel infModel = ModelFactory.createInfModel(reasoner, model);
String skos = "http://www.w3.org/2004/02/skos/core#";
Resource skosConcept = infModel.createResource( skos+"Concept" );
Resource instance = infModel.createResource("http://eg.com#Instance");
infModel.add(instance, RDF.type, skosConcept);
Property prefLabel = infModel.createProperty( skos+"prefLabel" );
Literal label = infModel.createLiteral( "a preferred label in English", "en" );
// either of these lines is fine
instance.addLiteral( prefLabel, label );
infModel.add( instance, prefLabel, label );
model.write( System.out, "N3" );
}
}
This code also shows the model, just so that we can see that the property is getting set as
<http://eg.com#Instance>
a <http://www.w3.org/2004/02/skos/core#Concept> ;
<http://www.w3.org/2004/02/skos/core#prefLabel>
"a preferred label in English"#en .

Related

grails domain constraints is not a map at runtime like docs suggest

The docs say that depending on version, accessing Domain.constraints or Domain.constrainedProperties should give a Map of key values.
https://grails.github.io/grails2-doc/2.5.4/ref/Domain%20Classes/constraints.html
At runtime the static constraints property is a Map such that the keys in the Map are property names and the values associated with the keys are instances of ConstrainedProperty:
However, using 2.5+, accessing the constraints property at runtime doesn't give a map, but a closure, and I can't access the ConstrainedProperty instances.
I tried using grails class utils to access the static property also
GrailsClassUtils.getStaticFieldValue(Domain,"constraints")//this is still a closure
GrailsClassUtils.getStaticFieldValue(Domain,"constrainedProperties")//null, this property doesn't exist below version 3.0
Property access doesn't work for me like the example in the docs
Domain.constraints //returns closure
but using the method getter does
Domain.getConstraints() //returns the map
See the project at https://github.com/jeffbrown/constraintsmapdemo.
https://github.com/jeffbrown/constraintsmapdemo/blob/master/grails-app/domain/demo/Widget.groovy:
package demo
class Widget {
int width
int height
static constraints = {
width range: 1..100
height range: 1..50
}
}
The test at https://github.com/jeffbrown/constraintsmapdemo/blob/master/test/unit/demo/WidgetSpec.groovy passes:
package demo
import grails.test.mixin.TestFor
import spock.lang.Specification
#TestFor(Widget)
class WidgetSpec extends Specification {
void "test accessing the constraints property"() {
when:
def propValue = Widget.constraints
then:
propValue instanceof Map
propValue.containsKey 'width'
propValue.containsKey 'height'
}
}
If you are not using static compilation, Widget.constraints will evaluate to the Map. If you are using static compilation, Widget.getConstraints() will return the Map but Widget.constraints will evaluate to the closure.

how to use type annotations in xtext?

How can I add a field like the following using the JvmModelInferrer?
public final #IdInstance long id;
What I already have is this:
members += domainId.toField('id', Long.TYPE.typeRef()) [
visibility = JvmVisibility.PUBLIC
final = true
]
which produces this java code:
public final long id;
But I cannot figure out how to add the IdInstance annotation to the type.
Note: adding the annotation to the field works, but is not what I want:
members += domainId.toField('id', Long.TYPE.typeRef()) [
visibility = JvmVisibility.PUBLIC
final = true
annotations += 'com.tmtron.dscontrol2.qual.IdInstance'.annotationRef()
]
produces:
#IdInstance
public final long id;
xbase does not support type annotations yet: see xtext#218
But there is an easy way to generate what we want:
JvmTypeReferenceBuilder.typeRef('#IdInstance long')
This will create a JvmUnknownTypeReference which just writes the provided string literally to the output (so make sure to get the imports right or use the fully qualified annotation).

neo4j java node dynamic properties

I am trying to create nodes of a specific type with properties which can be dynamic .
For Example : I can create a Person node with name,age,address properties. But these need not be the only properties when I create another Person node. This node can have name,age,address and an additional property salary. Using spring data or query DSL needs me to create Java POJO class Person with fixed number of instance variables name,age and address .
#NodeEntity
public class Person {
#GraphId private Long id;
private String name;
private String age;
private String address;
}
I cannot add a dynamic property for salary for another Person node. Is there a way I can achieve this ?
Dynamic properties are not supported in Neo4j-OGM at the moment (see https://jira.spring.io/browse/DATAGRAPH-555)
If you only interact with your graph via the OGM and do not have to query on individual dynamic properties, you could try a Map of properties with a custom Converter, that converts this Map to a String (like json). The OGM will then use this converter to serialize the map to and from the graph.
Note that because the values are squashed into a String, it is now not trivial to query on an individual dynamic property.
To create a custom converter you need to implement org.neo4j.ogm.typeconversion.AttributeConverter and provide the implementation to convert from a Map to String.
Then, annotate your map property in your domain entity like this:
#Convert(MoneyConverter.class)
Edit:
As pointed out by Michael, if the salary is the only extra optional property, then it makes sense to have this property but set it only when it has a value. Dynamic properties are overkill in this case. You may want to use dynamic properties when you have an unknown and arbitrary set of properties to be persisted with the node
You can workaround the limitations by creating a CompositeAttributeConverter saving each dynamic property in the graph (not only as JSON-String wich cannot be queried well - as mentioned by luanne in the accepted answer)
import java.lang.reflect.Field;
import java.util.*;
import org.neo4j.ogm.typeconversion.CompositeAttributeConverter;
public abstract class DynamicPropertiesConverter implements CompositeAttributeConverter<Map<String, ?>> {
private Set<String> blacklist;
public DynamicPropertiesConverter(Class<?> clazz) {
blacklist = new HashSet<>();
addAllFields(clazz);
}
public DynamicPropertiesConverter(Set<String> blacklist) {
this.blacklist = blacklist;
}
public void addAllFields(Class<?> type) {
for (Field field : type.getDeclaredFields()) {
blacklist.add(field.getName());
}
if (type.getSuperclass() != null) {
addAllFields(type.getSuperclass());
}
}
#Override
public Map<String, ?> toGraphProperties(Map<String, ?> value) {
Map<String, ?> result = new HashMap<>(value);
result.keySet().removeAll(blacklist);
return result;
}
#Override
public Map<String, ?> toEntityAttribute(Map<String, ?> value) {
return toGraphProperties(value);
}
}
Now you can create a special version of this converter:
public class DynamicNodePropertiesConverter extends DynamicPropertiesConverter {
public DynamicNodePropertiesConverter() {
super(Node.class);
}
}
And use it like this:
import java.util.Map;
import DynamicNodePropertiesConverter;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.typeconversion.Convert;
#NodeEntity
public class Node {
#Convert(DynamicNodePropertiesConverter.class)
private Map<String, Object> data;
/* getter and setter */
}

How are arguments passed into the parameter list of ClassMirror.newInstance(...)? [duplicate]

I'm perfectly willing to play with this until I get it right, but was hoping someone might give me a hint. The parameter is declared in the docs (gen-dartdocs/dart-mirrors/ClassMirror/newInstance.html) as
InstanceMirror newInstance(Symbol constructorName,
List positionalArguments,
[Map<Symbol,dynamic> namedArguments]);
There is a nice writeup on the format of positionalArguments and namedArguments in the docs. However, it is just a little on the abstract side of my current tolerance level.
A decent discussion also exists at
http://japhr.blogspot.com/2014/06/dart-factory-method-pattern.html
But, alas, no examples of actually passing args into the method.
In my case, I would like to simply pass two args, "title" and "description" into an unnamed subclass constructor.
Here's my code so far:
file: item.dart
import 'dart:mirrors';
abstract class Item {
String title;
String description;
factory Item(String type) {
MirrorSystem libs = currentMirrorSystem();
LibraryMirror lib = libs.findLibrary(new Symbol('app.models'));
Map<Symbol, Mirror> classes = lib.declarations;
// To do: handle exception if class not found
ClassMirror cls = classes[new Symbol(type)];
// TODO:
// verify each subclass has no-arg ctor
// determ how to pass args to ctor.
InstanceMirror inst = cls.newInstance(new Symbol(''), []);
return inst.reflectee;
}
// conflicts w/ Item factory
// Item(this.title, this.description);
}
And here's the class that gets instantiated:
file: model.dart
library app.models;
import 'item.dart' show Item;
/// The barebones model for a codelab. Defines constants used for validation.
class Codelab implements Item {
// ...
}
Finally, here is how the Item factory is called. ItemElement is the superclass of its own hierarchy, subclassed by CodelabElement:
file: item_element.dart:
import 'item.dart' show Item;
class ItemElement {
Item item;
final String itemType;
ItemElement() {
item = new Item(itemType);
}
// ...
}
And CodelabElement:
file: codelab_element.dart
import 'model.dart' show Codelab;
import 'item_element.dart' show ItemElement;
class CodelabElement extends ItemElement {
final itemType = "Codelab";
CodelabElement() : super() {}
//...
}
And then:
file: main.dart
void main() {
var element = new CodelabElement();
}
Currently, the new Codelab instance is returned from newInstance() (very cool), but it doesn't contain the inherited 'title' and 'description' attrs.
Maybe it has something to do with my being unclear on the usage of "extends" and "implements".
This should work
cls.newInstance(new Symbol(''), ['a', 1] /*,
{#arg1Name: 'arg1Value', #arg2Name: 'arg2Value'}*/ );
and is like
new MyClass('a', 1, arg1Name: 'arg1Value' /*, arg2Name: 'arg2Value'*/);
Just saw, Named arguments are not implemented.
You can try it in DartPad

Vaadin can't find BeanContainer's Id Property

I'm trying to create a table with a BeanContainer after populating it. However, when I try to run it, I get the following error message:
java.lang.IllegalStateException: Property RoomID not found
The relevant code is below (in which rooms can create a list of random Room objects). The Room class has a RoomID integer, and while it is a private variable the code produces the same error even if RoomID isn't private. I've also made sure that r_list actually contains Room instances.
BeanContainer<Integer, Room> r_cont = new BeanContainer<Integer, Room>(Room.class);
r_cont.setBeanIdProperty("RoomID");
//fetches all rooms and adds them to the bean container
List<Room> r_list = rooms.getRooms();
for (Room room: r_list)
r_cont.addBean(room);
EDIT: Here's the notable part of the Room object. I left out the initialization method and the methods for setting/getting the other variables.
package Entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Room")
public class Room {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="RoomID")
private int RoomID;
...
public int getRoomID(){
return RoomID;
}
...
}
The property name is not deducted from the the actual variable holding it, but from the getter/setter. This means it should be roomId (see e.g. Where is the JavaBean property naming convention defined?). If you are not sure about the properties you hold, you can debug it on the container with: .getContainerPropertyIds().

Resources