How to get the prefix and namespace list from Virtuoso, using Sesame - virtuoso

How to get the prefix and namespace list for a vocabulary (or Graph) in Virtuoso, like we have it in Sesame:
In Sesame, we are able to retrieve the prefix and namespace list for a vocabulary (repository) using RepositoryConnection object,
RepositoryResult<Namespace> nameSpaces = connection.getNamespaces();
but how do we get the same list for the vocabulary, when we upload it to Virtuoso.
VirtGraph gives default prefix and namespace list, but not giving the prefix and namespace list from the uploaded vocabulary.

The wording of your initial question suggests that you may think that "vocabulary", "Graph", and "repository" are all synonyms. They are not! A "repository" (also known as a data store) may hold one or many "Graphs", one or more of which might contain a "vocabulary" (or, more commonly in RDF parlance, an "ontology"), which describe the terminology used to describe some class(es) of entity(ies), with or without "instance data" (sometimes known as "records", which are the actual descriptions of some actual instances of those classes).
That said -- PREFIX (or #prefix) statements in RDF-Turtle, RDF-N3, and similar files are not actually part of the data; they are part of the serialization. Thus, they are not automatically persisted as prefixes or namespaces in the Virtuoso data store.
The Virtuoso Conductor provides a section for defining namespaces (http://{virtuoso-host-fqdn}:{port}/conductor/ → Linked Data → Namespaces). We generally recommend working through that interface, but experts can also work directly with the relevant SQL table, DB.DBA.SYS_XML_PERSISTENT_NS_DECL. Namespaces defined here are used when Virtuoso produces serialized output in formats which support CURIEs (a/k/a Compact URIs), and when Virtuoso interprets CURIEs in SPARQL queries and elsewhere.
You can see the currently defined namespaces through the built-in page, http://{virtuoso-host-fqdn}:{port}/sparql?help=nsdecl, as may be seen on DBpedia, or through any SQL connection (iSQL, ODBC, JDBC, etc.) --
SELECT NS_PREFIX,
NS_URL
FROM DB.DBA.SYS_XML_PERSISTENT_NS_DECL
ORDER BY LOWER(NS_PREFIX) ;
You can also use Sesame (now RDF4J) methods to get these, as in this snippet from the documentation and sample code we provide --
// test getNamespace
Namespace testns = null;
RepositoryResult<Namespace> namespaces = null;
boolean hasNamespaces = false;
try {
namespaces = con.getNamespaces();
hasNamespaces = namespaces.hasNext();
while (namespaces.hasNext()) {
Namespace ns = namespaces.next();
// LOG("Namespace found: (" + ns.getName() + " " + ns.getPrefix() + ")");
testns = ns;
}
}
catch (Exception e) {
log("Error[" + e + "]");
e.printStackTrace();
ok = false;
}
Our Providers also have methods for deleting and updating registered namespaces, which are implemented in the VirtuosoRepositoryConnection class, as discussed in the API docs for each Provider (RDF4J, Sesame 4, Sesame 2).
(ObDisclaimer: OpenLink Software produces Virtuoso, and employs me.)

Related

How to initialize a struct value fields using reflection?

I got a .ini configuration file that I want to use to initialize a Configuration struct.
I'd like to use the Configuration fields names and loop over them to populate my new instance with the corresponding value in the .ini file.
I thought the best way to achieve this might be reflection API (maybe I'm totally wrong, tell me...)
My problem here is that I cannot figure out how to access field's name (if it is at least possible)
Here is my code:
package test
import(
"reflect"
"gopkg.in/ini.v1"
)
type Config struct {
certPath string
keyPath string
caPath string
}
func InitConfig(iniConf *ini.File) *Config{
config:=new(Config)
var valuePtr reflect.Value = reflect.ValueOf(config)
var value reflect.Value = valuePtr.Elem()
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
if field.Type() == reflect.TypeOf("") {
//here is my problem, I can't get the field name, this method does not exist... :'(
value:=cfg.GetSection("section").GetKey(field.GetName())
field.SetString(value)
}
}
return config
}
Any help appreciated...
Use the type to get a StructField. The StructField has the name:
name := value.Type().Field(i).Name
Note that the ini package's File.MapTo and Section.MapTo methods implement this functionality.
While #MuffinTop solved your immediate issue, I'd say you may be solving a wrong problem. I personally know of at least two packages, github.com/Thomasdezeeuw/ini and gopkg.in/gcfg.v1, which are able to parse INI-style files (of the various level of "INI-ness", FWIW) and automatically populate your struct-typed values using reflection, so for you it merely amounts to properly setting tags on the fields of your struct (if needed at all).
I used both of these packages in production so am able to immediately recommend them. You might find more packages dedicated to parsing INI files on godoc.org.

What parts of an object are stored when it's saved into a session variable [duplicate]

The title is obvious, I need to know if methods are serialized along with object instances in C#, I know that they don't in Java but I'm a little new to C#. If they don't, do I have to put the original class with the byte stream(serialized object) in one package when sending it to another PC? Can the original class be like a DLL file?
No. The type information is serialized, along with state. In order to deserialize the data, your program will need to have access to the assemblies containing the types (including methods).
It may be easier to understand if you've learned C. A class like
class C
{
private int _m;
private int _n;
int Meth(int p)
{
return _m + _n + p;
}
}
is essentially syntactic sugar for
typedef struct
{
int _m;
int _n;
// NO function pointers necessary
} C;
void C_Meth(C* obj, int p)
{
return obj->_m + obj->_n + p;
}
This is essentially how non-virtual methods are implemented in object-oriented languages. The important thing here is that methods are not part of the instance data.
Methods aren't serialized.
I don't know about your scenario, but putting in a library (assembly / dll) and using that in the other end to deserialize gets you all.
Ps. you probably should create some ask some more questions with the factors involved in your scenario. If you are intending to dynamically send & run the code, you can create awful security consequences.
I was confused when .NET first came up with serialization. I think it came from the fact that most books and guides mention that it allows you to serialize your 'objects' as XML and move them around, the fact is that you are actually hydrating the values of your object so you can dehydrate them latter. at no point your are saving your whole object to disk since that would require the dll and is not contained in the XML file.

Languages supporting complete reflection

Only recently, I discovered that both Java and C# do not support reflection of local variables. For example, you cannot retrieve the names of local variables at runtime.
Although clearly this is an optimisation that makes sense, I'm curious as to whether any current languages support full and complete reflection of all declarations and constructs.
EDIT: I will qualify my "names of local variables" example a bit further.
In C#, you can output the names of parameters to methods using reflection:
foreach(ParameterInfo pi in typeof(AClass).GetMethods()[0].GetParameters())
Trace.WriteLine(pi.Name);
You don't need to know the names of the parameters (or even of the method) - it's all contained in the reflection information. In a fully-reflective language, you would be able to do:
foreach(LocalVariableInfo lvi in typeof(AClass).GetMethods()[0].GetLocals())
Trace.WriteLine(lvi.Name);
The applications may be limited (many applications of reflection are), but nevertheless, I would expect a reflection-complete language to support such a construct.
EDIT: Since two people have now effectively said "there's no point in reflecting local variable names", here's a basic example of why it's useful:
void someMethod()
{
SomeObject x = SomeMethodCall();
// do lots of stuff with x
// sometime later...
if (!x.StateIsValid)
throw new SomeException(String.Format("{0} is not valid.", nameof(x));
}
Sure, I could just hardcode "x" in the string, but correct refactoring support makes that a big no-no. nameof(x) or the ability to reflect all names is a nice feature that is currently missing.
Your introductory statement about the names of local variables drew my interest.
This code will actually retrieve the name of the local var inside the lambda expression:
static void Main(string[] args)
{
int a = 5;
Expression<Func<int>> expr = (() => a);
Console.WriteLine(expr.Compile().Invoke());
Expression ex = expr;
LambdaExpression lex = ex as LambdaExpression;
MemberExpression mex = lex.Body as MemberExpression;
Console.WriteLine(mex.Member.Name);
}
Also have a look at this answer mentioning LocalVariableInfo.
Yes, there are languages where this is (at least kind of) possible. I would say that reflection in both Smalltalk and Python are pretty "complete" for any reasonable definition.
That said, getting the name of a local variable is pretty pointless - by definition to get the name of that variable, you must know its name. I wouldn't consider the lack of an operation to perform that exact task a lacuna in the reflection facility.
Your second example does not "determine the name of a local variable", it retrieves the name of all local variables, which is a different task. The equivalent code in Python would be:
for x in locals().iterkeys(): print x
eh, in order to access a local var you have to be within the stackframe/context/whatever where the local var is valid. Since it is only valid at that point in time, does it matter if it is called 't1' or 'myLittlePony'?

Groovy DSL with embedded groovy scripts

I am writing a DSL for expressing flow (original I know) in groovy. I would like to provide the user the ability to write functions that are stored and evaluated at certain points in the flow. Something like:
states {
"checkedState" {
onEnter {state->
//do some groovy things with state object
}
}
}
Now, I am pretty sure I could surround the closure in quotes and store that. But I would like to keep syntax highlighting and content assist if possible when editing these DSLs. I realize that the closure COULD reference artifacts from the surrounding flow definition which would no longer be valid when executing the closure in a different context, and I am fine with this. In reality I would like to use the closure syntax for a non-closure function definition.
tl;dr; I need to get the closure's code while evaluating the DSL so that it can be stored in the database and executed by a script host later.
I don't think there is a way to get a closure's source code, as this information is discarded during compilation. Perhaps you could try writing an AST transformation that would make closure's syntax tree available at runtime.
If all you care about is storing the closure in the database, and you don't need later access to the source code, you can try serializing it and storing the serialized form.
Closure implements Serializable, and after nulling its owner, thisObject and delegate attributes I was able to serialize it, but I'm getting ClassNotFoundException on deserialization.
def myClosure = {a, b -> a + b}
Closure.metaClass.setAttribute(myClosure, "owner", null)
Closure.metaClass.setAttribute(myClosure, "thisObject", null)
myClosure.delegate = null
def byteOS = new ByteArrayOutputStream()
new ObjectOutputStream(byteOS).writeObject(myClosure)
def serializedClosure = byteOS.toByteArray()
def input = new ObjectInputStream(new ByteArrayInputStream(serializedClosure))
def deserializedClosure = input.readObject() // throws CNFE
After some searching, I found Groovy Remote Control, a library created specifically to enable serializing closures and executing them later, possibly on a remote machine. Give it a try, maybe that's what you need.

How can you get NVelocity to initialize correctly?

I can't get NVelocity to initialize. I'm not trying to do anything complicated, so it's just fine if it initializes at the defaults, but it won't even do that.
This:
VelocityEngine velocity = new VelocityEngine();
ExtendedProperties props = new ExtendedProperties();
velocity.Init(props);
Results in: "It appears that no class was specified as the ResourceManager..."
So does this:
VelocityEngine velocity = new VelocityEngine();
velocity.Init();
I can find precious little documentation on what the properties should be, nor how to get it to initialize with the simple defaults. Can anyone point to a resource?
A lot of pages point back to this page:
http://www.castleproject.org/others/nvelocity/usingit.html
But this page skips over the (seemingly) most important point -- how to set the properties and what to set them to.
I just want to load a simple template from a file.
Here's what I found out --
I was using the original NVelocity library, which hasn't had an update since 2003. I think it's a dead project.
I switched to the Castle Project version, and it's much easier -- in fact, it runs much like the examples on the page I linked to. It seems to set intelligent defaults for properties. I can initialize it without any properties set, but the template directory defaults to ".", so I generally set that one (do it before running "init").
To get the correct DLL, you need to download the latest NVelocity release (as of this writing it's 1.1).
Castle Project Download Page
You need to include the following files in your assembly, and make sure that their type is set to "Resource"
src\Runtime\Defaults\directive.properties
src\Runtime\Defaults\nvelocity.properties
These will then be found by ResourceLocator
src\Runtime\Resource\Loader\ResourceLocator.cs
If you get an exception on GetManifestResourceNames() as I did when trying to run Dvsl, then try modifying the ResourceLocator constructor to catch and ignore the error since the required files are in your local assembly (if you included them above) and the exception is only thrown by external assemblies (no idea why).
foreach(Assembly a in assemblies) {
String prefix = a.FullName.Substring(0,a.FullName.IndexOf(",")).ToLower();
try
{
String[] names = a.GetManifestResourceNames();
foreach (String s in names)
{
if (s.ToLower().Equals(fn) || s.ToLower().Equals(prefix + "." + fn))
{
this.filename = s;
assembly = a;
isResource = true;
}
}
} catch {
}
}

Resources