How to debug NullPointerException on getOntClass()? - nullpointerexception

I'm working with Jena and I'm trying to create a Class in my ontology during runtime.
This is my function to create the class :
static public boolean createClass(Model model, String className){
String namespace = "http://www.myontologyexemple.com#";
OntModel ontModel = ModelFactory.createOntologyModel( OntModelSpec.RDFS_MEM, model);
OntClass myClass = ontModel.createClass(namespace + className);
OntClass mother = ontModel.getOntClass(namespace + "mother");// returns null
m2m.addSubClass(myClass);
return(myClass.getSuperClass().equals(mother));
}
As Commented on my code I get a null when trying to get the "mother" class. I tested and the class exists under the namespace.
Also, not that it may be the source of the problem, but this code is part of a bundle on Karaf.
Thanks in advance for your help.

Okay Turns out I was using the wrong Spec for my model that's why it couldn't create the class. Instead of OntModelSpec.RDFS_MEM I used OntModelSpec.RDFS_MEM_RDFS_INF which I should have seen sooner and not after 3 days of trying to solve the problem.

Related

Issue accessing fields in generic base class using Fody

Consider the following test code structure:
class TestClass<T>
{
public object TestObject;
}
class TestClass2<T> :TestClass<T>
{
public int TestMethod()
{}
}
When I add Instruction.Create(OpCodes.Ldfld, TestObjectField) to TestMethod, I get the following result:
ldfld class Object TestNamespace.TestClass`1::TestObject
This causes an issue in the secure plugin system of Dynamics CRM (more information could be found here). However, when I add TestObject = new object() to TestMethod, I get the following result, which runs fine:
ldfld class Object class TestNamespace.TestClass`1<!T>::TestObject
This only happens when the object I am trying to access is in a generic base class. Is there a way that I can simulate the desired result from within Fody please?
UPDATE:
I managed to partially solve the issue by using the following lines:
var testObjectFieldRef = testObjectFieldDefinition?.Resolve().GetGeneric();
var testClassTypeRef = testObjectFieldRef?.DeclaringType.Resolve().GetGeneric();
if (testClassTypeRef != null)
{
testObjectFieldRef.DeclaringType = testClassTypeRef;
}
It seems that by default the ModuleDefinition does not provide a generic type/field definition; so it has to be done explicitly. In addition, the types of the generic parameters are not specified, so it's still an issue.
I managed to solve this issue by using the following code (reference):
var genericBaseType = (GenericInstanceType) testClassTypeRef.BaseType;
var genericArgs = genericBaseType .GenericArguments;
var fullBaseTypedName = genericBaseType.ElementType.MakeGenericInstanceType(genericArgs.ToArray()).FullName
Which returns ldfld class Object class TestNamespace.TestClass`1<!T>::TestObject as required. It will also fill in the type of the type parameter (in place of <!T>) if given in the derived class.

VB.net anonymous class with inheritance

Imagine I have class like this :
Class A
Public Function Some(str As String) As String
Return "Some " + str
End Function
End Class
I have consuming code like this :
Public Sub Foo()
Dim thisWorks = New With {.prop = "thing"}
Dim thisDoesntWork = New inherits A with { .prop = Some("thing") }
End Sub
I'm trying to create an anonymous type with inheritance so that I can use the methods within. Is this possible ?
Use case : I'm trying to create a class that has methods like Select, From etc. that would help in cleaner query construction. In the consuming code, I would just create an anonymous type inheriting from the class and use the methods.
What you want is not possible (at least not the way you describe it).
From what I think I understood ; you should try to mimic what has been donne for Linq ; an interface (like IEnumerable) with all the method you want (or maybe an abstract class bu that prevent you to inherit from something else) + something else (probably a module if you want them as extension method) defining the Select etc. acting on the interface.
From that point you can create classes which implement the interface and use your custom Select etc. on them

FluentNHibernate AutoMapping : ClassConvention Does not work

I have a model library that I want to automatically build its NHibernate mappings using FluentNhibernate.
There's a convention that I'd like to add to this model and that is each table name ends with 's'.
So here's what I do :
new AutoPersistenceModel()
.AddEntityAssembly(typeof(User).Assembly)
.Conventions.Add(typeof(ClassConvention))
.WriteMappingsTo(#"E:\Temp\");
Here's the code of ClassConvention :
private class ClassConvention:IClassConvention
{
public void Apply(IClassInstance instance)
{
instance.Table(instance.EntityType.Name+"s");
}
}
but it simply doesn't work.No table attribute is added to class tag when I run this code.
Please help me understand what's wrong with my code ?
Update:
I have debugged my code and I am sure that this line :
instance.Table(instance.EntityType.Name+"s");
is called.
Your convention defining class should be public not private

Linq to SQL - Attribute based mapping - cannot instantiate new object with no arguments

I want to extend Linq's DataContext class to implement the ORM. Currently my model looks like this:
public class Trial : DataContext
{
public Trial(string connectionString) : base(connectionString) { }
[Column(DbType = "System.Guid", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
public Guid TrialID { get; set; }
//...
}
However when I try to instantiate a new Trial object to insert it into the database I get an error complaining that Trial does not have a constructor that takes 0 arguments. When I try to create such a constructor, VS complains that DataContext does not have a constructor that takes 0 arguments.
Am I missing something here? How do I seperate the data context from the model definition?
(First time using Linq!)
Thanks in advance,
Max.
Your data context that represents the database view should inherit from DataContext. It should expose Tables where T is the entities (rows) that you want to add. Try generating a model from the database using the designer or SQLMetal and take a closer look at the generated code to see what's going on.

Dozer BeanFactory: How to implement it?

I have looked at the Dozer's FAQs and docs, including the SourceForge forum, but I didn't see any good tutorial or even a simple example on how to implement a custom BeanFactory.
Everyone says, "Just implement a BeanFactory". How exactly do you implement it?
I've Googled and all I see are just jars and sources of jars.
Here is one of my BeanFactories, I hope it helps to explain the common pattern:
public class LineBeanFactory implements BeanFactory {
#Override
public Object createBean(final Object source, final Class<?> sourceClass, final String targetBeanId) {
final LineDto dto = (LineDto) source;
return new Line(dto.getCode(), dto.getElectrified(), dto.getName());
}
}
And the corresponding XML mapping:
<mapping>
<class-a bean-factory="com.floyd.nav.web.ws.mapping.dozer.LineBeanFactory">com.floyd.nav.core.model.Line</class-a>
<class-b>com.floyd.nav.web.contract.dto.LineDto</class-b>
</mapping>
This way I declare that when a new instance of Line is needed then it should create it with my BeanFactory. Here is a unit test, that can explain it:
#Test
public void Line_is_created_with_three_arg_constructor_from_LineDto() {
final LineDto dto = createTransientLineDto();
final Line line = (Line) this.lineBeanFactory.createBean(dto, LineDto.class, null);
assertEquals(dto.getCode(), line.getCode());
assertEquals(dto.getElectrified(), line.isElectrified());
assertEquals(dto.getName(), line.getName());
}
So Object source is the source bean that is mapped, Class sourceClass is the class of the source bean (I'm ignoring it, 'cause it will always be a LineDto instance). String targetBeanId is the ID of the destination bean (too ignored).
A custom bean factory is a class that has a method that creates a bean. There are two "flavours"
a) static create method
SomeBean x = SomeBeanFactory.createSomeBean();
b) instance create method
SomeBeanFactory sbf = new SomeBeanFactory();
SomeBean x = sbf.createSomeBean();
You would create a bean factory if creating and setting up your bean requires some tricky logic, like for example initial value of certain properties depend on external configuration file. A bean factory class allows you to centralize "knowledge" about how to create such a tricky bean. Other classes just call create method without worying how to correctly create such bean.
Here is an actual implementation. Obviously it does not make a lot of sense, since Dozer would do the same without the BeanFactory, but instead of just returning an object, you could initialized it somehow differently.
public class ComponentBeanFactory implements BeanFactory {
#Override
public Object createBean(Object source, Class<?> sourceClass,
String targetBeanId) {
return new ComponentDto();
}
}
Why do you need a BeanFactory anyways? Maybe that would help understanding your question.