Jena custom datatype - java

For a GeoSPARQL test project I want to have a custom datatype set in Jena. Howerver when I try this through the example provided at the Jena website, it still doesn't work. I get the following result:
_:b0 <http://www.opengis.net/ont/geosparql#asWKT> "POINT (52.83525867111958 6.870789811954563)^^http://www.opengis.net/ont/sf#wktLiteral "^^<java:com.hp.hpl.jena.rdf.model.impl.LiteralImpl> .
And of course I don't want the java:com.hp.hpl.jena.rdf.model.impl.LiteralImpl but http://www.opengis.net/ont/sf#wktLiteral because I wan to work with GeoSPARQL. On this page they have example data that works perfectly with my triple store and spatial index. But the above data doesn't work at all with spatial indexing.
So, my question is, I do I define a custom datatype in my RDF in Jena?

The syntax is
"POINT (52.83525867111958 6.870789811954563)"^^<http://www.opengis.net/ont/sf#wktLiteral>

I just found the answer to my question after a lot of trial and error. To add a custom RDFDatatype to my RDF model I first had to create my own class which extends BaseDatetype and which I called WktLiteral, looking like this:
public class WktLiteral extends BaseDatatype {
public static final String TypeURI = "http://www.opengis.net/ont/sf#wktLiteral";
public static final String CRS84 = "<http://www.opengis.net/def/crs/OGC/1.3/CRS84>";
public static final RDFDatatype wktLiteralType = new WktLiteral();
private WktLiteral() {
super(WktLiteral.TypeURI);
}
/**
* Convert a value of this datatype out
* to lexical form.
*/
public String unparse(Object value) {
return value.toString();
}
/**
* Parse a lexical form of this datatype to a value
*/
public Object parse(String lexicalForm) {
return new TypedValue(String.format("%s %s", WktLiteral.CRS84, lexicalForm), this.getURI());
}
/**
* Compares two instances of values of the given datatype.
* This does not allow rationals to be compared to other number
* formats, Lang tag is not significant.
*
* #param value1 First value to compare
* #param value2 Second value to compare
* #return Value to determine whether both are equal.
*/
public boolean isEqual(LiteralLabel value1, LiteralLabel value2) {
return value1.getDatatype() == value2.getDatatype()
&& value1.getValue().equals(value2.getValue());
}
Where it was quite important to return a TypedLiteral in the parse() method. After which I had to do the following to add something to my RDF model:
TypeMapper.getInstance().registerDatatype(WktLiteral.wktLiteralType);
item.addLiteral(GeoSPARQL.asWKT, ResourceFactory.createTypedLiteral(geom, WktLiteral.wktLiteralType));
Where GeoSPARQL.asWKT is the predicate in the GeoSPARQL vocabulary that I generated through schemagen. geom is the geometry object as well known text and WktLiteral.wktLiteralType is an instance of the above class.
In conclusion the result was the following (notation 3):
_:b0 <http://www.w3.org/2003/01/geo/wgs84_pos#lat_long> "POINT (51.61821756986111 5.542408362751153)" .
thus exactly what I wanted... Thanks for all the input.

Related

JAutodoc: getter comment template is merged with default comment behavior

I am trying to configure JAutodoc such that getter comments are generated containing only the #returns tag, like so:
/**
* #returns The non-null {#linkplain Foo foo} of this {#link IBar}.
*/
public Foo getFoo();
I have configured my getter template to produce this:
However, something must be wrong with my general JAutodoc settings, because what I get instead is a hybrid of my template and a comment parsed from the method name:
/**
* Get foo.
* #returns The non-null {#linkplain Foo foo} of this {#link IBar}.
*/
public Foo getFoo();
These are my settings:
I have removed the 'get' replacement from the replacements list, as well as unchecked the 'etter from field comment' setting as advised in this discussion, but it has not made a noticeable difference. I have also attempted to uncheck the 'Create comment from element name' setting, despite my example getter being part of an interface (in which case there is no element to get the comment from), but JAutodoc doesn't seem to care about that.
I have also tried restarting Eclipse after making each of these changes, in case that mattered. So far, nothing is working. It almost appears as if the comment behavior of getters is hard-coded. Can someone please shed some light on this?
TL;DR
JAutodoc, in its current form, can not do what you want it to do. This is because you are asking for incomplete Javadocs.
Details
(This was fun, and I hope you appreciate the effort :-)
This is a case where you are asking JAutodoc to create incomplete Javadocs. i.e. you are asking for no documentation in the Javadoc. (I personally find the repetitiveness on simple getter annoying too BTW).
The steps that JAutodoc are going through internally is:
Applying your template, so the comment looks exactly as you want - for a moment in time.
This is the bit of code that applies the template. Using your example, the member parameter below is your getFoo method and, as there is no existing comment in your code when you first apply the auto-comment, so the jdi parameter is empty (jdi.isEmpty() == true).
When the template is applied, text looks exactly as you want it too. text gets parsed just as any Javadoc comment would and returned.
From net.sf.jautodoc.source.JavadocCreator:
public JavadocInfo applyTemplate(final IMember member, final JavadocInfo jdi) throws Exception {
final JavadocInfo templateJdi = new JavadocInfo();
final String text = JAutodocPlugin.getContext().getTemplateManager().applyTemplate(member,
config.getProperties());
if (text != null && text.length() > 0) {
templateJdi.parseJavadoc(text);
}
return jdi.isEmpty() ? templateJdi : jdi.merge(templateJdi);
}
Now the JavadocInfo that was returned from applyTemplate is passed to createJavadoc. In createJavadoc the code checks if there is a comment (excluding the #params, #return, etc). As there is not any, it tries to insert some automatically from the information available. Simplistically, it just un-camel-cases the name of the method and makes that the comment.
From net.sf.jautodoc.source.JavadocCreator
public String createJavadoc(final IMethod method, final String indent, final String lineSeparator,
final JavadocInfo jdi) throws JavaModelException {
final List<String> text = jdi.getComment();
if (text.isEmpty()) {
if (config.isCreateDummyComment()) {
if (method.isConstructor()) {
text.add(Constants.JDOC_CONSTRUCTOR);
}
else if (method.isMainMethod()) {
text.add(Constants.JDOC_MAIN);
}
else {
String comment = CommentManager.createComment(config, method.getElementName(),
CommentManager.METHOD, true, true, CommentManager.FIRST_TO_UPPER);
text.add(comment + Constants.DOT);
}
}
else {
text.add("");
}
}
else {
checkForDot(text);
}
Now the code that calls the above two methods is this:
From net.sf.jautodoc.source.SourceManipulator.addJavadoc(IMember):
if (config.isCreateDummyComment()) {
jdi = javadocCreator.applyTemplate(member, jdi);
}
newJavadoc = javadocCreator.createJavadoc((IMethod) member, indent, lineDelimiter, jdi);
As you can see from these code snippets, both applying your template and creating the comment part (that you don't want!) is controlled by the same if statement config.isCreateDummyComment(). That if statement connects to the Create comment from element name option.
Examples
This issue is not happening because the method is a getter, but applies everywhere. Assume you have this bit of code:
/**
* #param myFirstParam this is important and I documented it
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
And you apply JAutodoc to it (with Complete existing Javadoc) then you get:
With Create comment from element name unset:
/**
*
*
* #param myFirstParam this is important and I documented it
* #param anotherParamHere
* #return
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
With Create comment from element name set:
/**
* Do this and that.
*
* #param myFirstParam this is important and I documented it
* #param anotherParamHere the another param here
* #return the int
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
Getting the source
I couldn't find the source on any of the usual suspects (github, etc), but it is available for download here: http://sourceforge.net/projects/jautodoc/files/jautodoc/1.13.0/
So you could, if you desired, edit the source and rebuild your plug-ins. Or file a feature request with the dev.
In Conclusion
JAutodoc, in its current form, can not do what you ask it to do. However, this is essentially by design, because if you say you want to Create comment from element name automatically (internally called Create Dummy Comment) then you want fully complete Javadoc to be created for you.
Finally, keep in mind if there is no comment, then nothing appears in the method summary table and your generated Javadocs simply look incomplete.

Java : Convert Object consisting enum to Json Object

I am using org.json library to convert Object to Json format. Kindly check the below code snippet.
public enum JobStatus implements Serializable{
INCOMPLETE,
INPROGRESS,
ABORTED,
COMPLETED
}
public class Job implements Serializable {
private string id;
private JobStatus status;
...
}
...
// Create Job Object
Job job = new Job("12345", JobStatus.INPROGRESS);
// Convert and print in JSON format
System.out.println(new JSONObject(job).toString());
It shows the output like this :
{"id":"12345", "status" : {}}
It shows blank and adds Curly bases. What does it mean? Is anybody gone through this problem?
First of all I highly recommend do not use this library (org.json), this is very old and unsupported (as i know) library. I suggest Jackson or Gson.
But if you really need JSONObject, you can add getter into enum:
public enum JobStatus implements Serializable{
INCOMPLETE,
INPROGRESS,
ABORTED,
COMPLETED;
public String getStatus() {
return this.name();
}
}
result of serialization:
{"id":"12345","status":{"status":"INPROGRESS"}}
As I know, JSONObject don't support correct serialization of enums which not have any additional data inside.
ObjectMapper mapper= new ObjectMapper();
new JSONObject(mapper.writeValueAsString(job));
would do the trick. Now Enums and DateTime types looks normal and is converted properly in json objects.
I came to this page as a person seeking answer and my research helped me to answer this question.
It seems JSONObject doesn't support enums. You could alter your Job class to add a getter like this:
public String getStatus() {
return status.name();
}
then, invoking new JSONObject(job).toString() produces:
{"id":"12345","status":"INPROGRESS"}
for me, i made an interface that shuold be implemented by any enum i will have to use in Json, this interface forces the enum to know the proper enum itself from a value, and also it should return a value ... so every enum.CONSTANT is mapped to a value of any type (weather a number or a String)
so when i want to put this enum in a Json Object, i ask the enum.CONSTANT to give me it's value, and when i have this value (from Json), i can request from the enum to give me the proper enum.CONSTANT mapped to this value
the interface is as follows (you can copy it as it is) :
/**
*
* this interface is intended for {#code enums} (or similar classes that needs
* to be identified by a value) who are based on a value for each constant,
* where it has the utility methods to identify the type ({#code enum} constant)
* based on the value passed, and can declare it's value in the interface as
* well
*
* #param <T>
* the type of the constants (pass the {#code enum} as a type)
* #param <V>
* the type of the value which identifies this constant
*/
public interface Valueable<T extends Valueable<T, V>, V> {
/**
* get the Type based on the passed value
*
* #param value
* the value that identifies the Type
* #return the Type
*/
T getType(V value);
/**
* get the value that identifies this type
*
* #return a value that can be used later in {#link #getType(Object)}
*/
V getValue();
}
now here is an example for a small enum implementing this interface:
public enum AreaType implements Valueable<AreaType, Integer> {
NONE(0),
AREA(1),
NEIGHBORHOOD(2);
private int value;
AreaType(int value) {
this.value = value;
}
#Override
public AreaType getType(Integer value) {
if(value == null){
// assume this is the default
return NONE;
}
for(AreaType a : values()){
if(a.value == value){ // or you can use value.equals(a.value)
return a;
}
}
// assume this is the default
return NONE;
}
#Override
public Integer getValue() {
return value;
}
}
to save this enum in a Json :
AreaType areaType = ...;
jsonObject.put(TAG,areaType.getValue());
now to get your value from a Json Object :
int areaValue = jsonObject.optInt(TAG,-1);
AreaType areaType = AreaType.NONE.getType(areaValue);
so if the areaValue is 1 for example, the AreaType will be "Area", and so on
Similar to what #Denys Denysiuk has answered. But if you want to return any value instead of String We can use like this. In below example i wanted to return value 1, or 15 instead of String
#Getter
public enum PaymentCollectionDay {
FIRST_OF_MONTH(1), FIFTEENTH_OF_MONTH(15);
PaymentCollectionDay(int day) {
this.day = day;
}
#JsonValue
final int day;
}

Creating an enum in DELPHI

I have an enum codes in JAVA. I convert all JAVA code to DELPHI.
I almost done, but i stucked in here. I have no idea, how to convert enum to Delphi.
I am wondering, this code can be convert to Delphi ?
/**
* Enum describing the databin class ID's. Methods exist for getting the
* KakaduClassID and the StandardClassID. I have also included the string
* representations of the databins as defined for cache model updates.
*
*
*/
public enum JPIPDatabinClass {
/** Precinct data bin class. */
PRECINCT_DATABIN(KakaduConstants.KDU_PRECINCT_DATABIN, JPIPConstants.PRECINCT_DATA_BIN_CLASS, "P"),
/** Tile Header data bin class. */
TILE_HEADER_DATABIN(KakaduConstants.KDU_TILE_HEADER_DATABIN, JPIPConstants.TILE_HEADER_DATA_BIN_CLASS, "H"),
/** Tile data bin class. */
TILE_DATABIN(KakaduConstants.KDU_TILE_DATABIN, JPIPConstants.TILE_DATA_BIN_CLASS, "T"),
/** Main Header data bin class. */
MAIN_HEADER_DATABIN(KakaduConstants.KDU_MAIN_HEADER_DATABIN, JPIPConstants.MAIN_HEADER_DATA_BIN_CLASS, "Hm"),
/** Meta data bin class. */
META_DATABIN(KakaduConstants.KDU_META_DATABIN, JPIPConstants.META_DATA_BIN_CLASS, "M");
/** The classID as an integer as per the Kakadu library. */
private int kakaduClassID;
/** The classID as an integer as per the JPEG2000 Part-9 standard. */
private int standardClassID;
/**
* The classID as a string as per the JPEG2000 Part-9 standard. Used for
* cache model updates.
*/
private String jpipString;
/**
* Constructor.
*
* #param _kakaduClassID
* #param _standardClassID
* #param _jpipString
*/
JPIPDatabinClass(int _kakaduClassID, int _standardClassID, String _jpipString) {
kakaduClassID = _kakaduClassID;
standardClassID = _standardClassID;
jpipString = _jpipString;
}
/** Returns the classID as an integer as per the Kakadu library. */
public int getKakaduClassID() {
return kakaduClassID;
}
/** Returns the classID as an integer as per the JPEG2000 Part-9 standard. */
public int getStandardClassID() {
return standardClassID;
}
/**
* Returns the classID as a string as per the JPEG2000 Part-9 standard. Used
* for cache model updates.
*/
public String getJpipString() {
return jpipString;
}
};
This Enum can easily be translated to a plain old Delphi class which has a three-argument constructur like the Java Enum, and three read-only public properties.
JPIPDatabinClass = class(TObject)
private
...
public
constructor Create(AKakaduClassID: Integer; AStandardClassID: Integer; AJPIP: string);
property KakaduClassID: Integer; read FKakaduClassID;
property StandardClassID: Integer; read FStandardClassID;
property JPIP: string; read FJPIP;
end;
and 'singleton style' instances:
function PRECINCT_DATABIN: JPIPDatabinClass;
function TILE_HEADER_DATABIN: JPIPDatabinClass;
...
implementation
var
FPRECINCT_DATABIN: JPIPDatabinClass;
FTILE_HEADER_DATABIN: JPIPDatabinClass;
...
FPRECINCT_DATABIN := JPIPDatabinClass.Create( ... );
FTILE_HEADER_DATABIN := JPIPDatabinClass.Create( ... );
...
function PRECINCT_DATABIN: JPIPDatabinClass;
begin
Result := FPRECINCT_DATABIN;
end;
function TILE_HEADER_DATABIN: JPIPDatabinClass;
begin
Result := FTILE_HEADER_DATABIN;
end;
...
Note: the disadvantage of this approach is that does not create real Delphi enum types, it only emulates the Java enum type as immutable Delphi objects.

Mybatis No Getter Property

I'm working with Mybatis 3.2.6 and implementing a custom resulthandler. I've done this before using a simple datatype parameter and have had no problems. This time around I need to pass in several arguments... The signature I'm using is
session.select(statement, parameter, handler);
For parameter I've created a simple POJO to easily send in what I need. It is as follows:
public class DifferenceParam {
private int current;
private int compare;
private String table;
private String comparator;
/**
* Constructor excluding comparator. Will default a value of
* "code" to compare content on, e.g., <br/>
* {#code select * from a minus select * from b where a.code = b.code } <br/>
* #param table
* #param current
* #param compare
*/
public DifferenceParam(String table, int current, int compare) {
this(table, "code", current, compare);
}
/**
* Constructor providing a specific column to compare on, e.g. <br/>
* {#code select * from a minus select * from b where a.[comparator] = b.[comparator] } <br/>
* #param table
* #param comparator
* #param current
* #param compare
*/
public DifferenceParam(String table, String comparator, int current, int compare) {
this.table = table;
this.comparator = comparator;
this.current = current;
this.compare = compare;
}
/** Appropriate setters and getters to follow **/
}
The handler implementation is irrelevant at the moment, because I get an exception well in advance... The query I'm executing is:
<select id="getCodeSetModifications" parameterType="DifferenceParam" resultType="Code">
select *
from
(
select * from ${param.table} where revision_seq = #{param.current}
minus
select * from ${param.table} where revision_seq = #{param.compare}
) a, ${param.table} b
where a.${param.comparator} = b.${param.comparator}
and b.revision_seq = #{param.compare}
</select>
Here is the interface as well
public List<Code> getCodeSetModifications(#Param("param") DifferenceParam param);
The problem I'm having is that execution via a mapper e.g.,
session.getMapper(DifferenceParam.class);
works just fine, but when I invoke through a select on the session I get the following exception.
Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'param' in 'class com.mmm.his.cer.cerval.uidifference.map.param.DifferenceParam'
Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'param' in 'class com.mmm.his.cer.cerval.uidifference.map.param.DifferenceParam'
I've debugged as far as I can go into Mybatis, but am having no luck.
Thanks in advance...
When you use session.getMapper(DifferenceParam.class);, mybatis looks for #Param annotation and uses it's value in query.
When you invoke session.select(statement, parameter, handler);, such mapping doesn't occur.
Try to add public DifferenceParam getParam() { return this; } to DifferenceParam to workaround this.
when the MyBatis query only have one param. Don't need #{param.} reference.
because it default use the only param.
so when u use ${param.table}, it actually using #{DifferenceParam.param.table}.
because it think the ${param.} inside of the #{DifferenceParam.}

Java Crit-bit Trees

Is there a built-in data structure in Java to represent a Crit-bit tree? Or any libraries available that might provide this functionality? I would also accept brief code as an answer, if one can be implemented in a simplistic brief way.
Did you try the radixtree java project?
You might find in it the structure you are looking for, like the:
RadixTree class
(extract):
/**
* This interface represent the operation of a radix tree. A radix tree,
* Patricia trie/tree, or crit bit tree is a specialized set data structure
* based on the trie that is used to store a set of strings. In contrast with a
* regular trie, the edges of a Patricia trie are labelled with sequences of
* characters rather than with single characters. These can be strings of
* characters, bit strings such as integers or IP addresses, or generally
* arbitrary sequences of objects in lexicographical order. Sometimes the names
* radix tree and crit bit tree are only applied to trees storing integers and
* Patricia trie is retained for more general inputs, but the structure works
* the same way in all cases.
*
* #author Tahseen Ur Rehman
* email: tahseen.ur.rehman {at.spam.me.not} gmail.com
*/
public interface RadixTree<T> {
/**
* Insert a new string key and its value to the tree.
*
* #param key
* The string key of the object
* #param value
* The value that need to be stored corresponding to the given
* key.
* #throws DuplicateKeyException
*/
public void insert(String key, T value) throws DuplicateKeyException;
RadixTreeNode class
(extract):
/**
* Represents a node of a Radix tree {#link RadixTreeImpl}
*
* #author Tahseen Ur Rehman
* #email tahseen.ur.rehman {at.spam.me.not} gmail.com
* #param <T>
*/
class RadixTreeNode<T> {
private String key;
private List<RadixTreeNode<T>> childern;
private boolean real;
private T value;
/**
* intailize the fields with default values to avoid null reference checks
* all over the places
*/
public RadixTreeNode() {
key = "";
childern = new ArrayList<RadixTreeNode<T>>();
real = false;
}
Another option is rkapsi's patricia-trie, or if you're looking for something a little less complicated that you can hack on yourself, you can try his simple-patricia-trie.
I've also got a functional-critbit implementation available that's focused on space-efficiency (though its performance is fine, as well). It comes in both mutable and immutable flavors.
try concurrent-trees
on gradle:
compile 'com.googlecode.concurrent-trees:concurrent-trees:2.4.0'

Categories

Resources