Can't Instantiate Windsor Custom Component Activator - castle-windsor

I'm getting an exception calling Resolve:
KernelException: Could not instantiate custom activator
Inner Exception:
{"Constructor on type 'MyProj.MyAdapter`1[[MyProj.MyBusinessObject, MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found."}
There's definitely a public parameterless constructor there (and I've verified this using reflection at runtime)...so I figure the problem might have to do with the fact that it's generic? I've tried getting the component model object and setting RequiresGenericArguments to true, but that hasn't gotten me anywhere.
Any help would be much appreciated! Thanks.

Windsor is not using default constructor to instantiate activators.
The new version throws a more helpful exception message:
Castle.MicroKernel.KernelException : Could not instantiate custom activator
----> System.ArgumentException : Type Castle.Windsor.Tests.ActivatorWithoutCorrectConstructor does not have a public constructor matching arguments of the following types:
Castle.Core.ComponentModel
Castle.MicroKernel.DefaultKernel
Castle.MicroKernel.ComponentInstanceDelegate
Castle.MicroKernel.ComponentInstanceDelegate
So you need a constructor like this
public YourActivator(ComponentModel model, IKernel kernel,
ComponentInstanceDelegate onCreation,
ComponentInstanceDelegate onDestruction)

Related

Corda query throws "com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class"

I'm developing cordapp using the example-cordapp project as a reference. I've been able to commit a transaction to the ledger and even run querias on the node to see if it's really there. However, when I try to run query from my Spring Boot application, I get this error.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.springframework.http.converter.HttpMessageConversionException: JSON mapping problem:
java.util.Collections$UnmodifiableRandomAccessList[0]->net.corda.core.contracts.StateAndRef["state"]-
>net.corda.core.contracts.TransactionState["data"]-
>com.mypackage.states.MyState["party"]; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class
(through reference chain: java.util.Collections$UnmodifiableRandomAccessList[0]-
>net.corda.core.contracts.StateAndRef["state"]->net.corda.core.contracts.TransactionState["data"]-
>com.mypackage.states.MyState["party"])] with root cause
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~
[na:1.8.0_251]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
Here's the request code
#GetMapping(value = [ "/api/v1/states" ], produces = [MediaType.APPLICATION_JSON_VALUE])
fun getMyIOUs(): ResponseEntity<List<StateAndRef<MyState>>> {
val myStates = proxy.vaultQueryBy<MyState>().states
return ResponseEntity.ok(myStates)
}
And here's the state code
#BelongsToContract(com.sentinel.contract.SharingInformationContract::class)
class SharingInformationState(
val party: Party,
val dataOwnerId: Long,
val dataBuyerId: Long,
override val linearId: UniqueIdentifier = UniqueIdentifier()) : LinearState, QueryableState {
override val participants: List<AbstractParty> = listOf(party)
override fun generateMappedObject(schema: MappedSchema): PersistentState {
return when (schema) {
SharingInformationSchemaV1 -> SharingInformationSchemaV1.PersistentSharingInformation(
party,
dataOwnerId,
dataBuyerId,
linearId.id
)
else -> throw IllegalArgumentException("Unrecognised schema $schema")
}
}
override fun supportedSchemas(): Iterable<MappedSchema> = listOf(SharingInformationSchemaV1)
}
There's little information about this issue on the internet. Some suggest it is connected to the classpath, that something is duplicated there, but I don't know how to check. Also, this error isn't connected to the Party type. I've tried to add #JsonIgnore on a party, but then it throws on the other field. Persistence of this field in mapping schema also doesn't matter. I've tried persisting and not persisting, it changes nothing. Thanks in advance!
I believe this is because you are missing Corda Jackson support library which is required to convert Corda objects to json.
Add this to your dependencies in the build.gradle
compile "net.corda:corda-jackson:$corda_release_version"
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/client/build.gradle#L19
Also, make sure you have a MappingJackson2HttpMessageConverter bean configured.
#Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
ObjectMapper mapper = JacksonSupport.createDefaultMapper(partyAProxy());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(mapper);
return converter;
}
https://github.com/corda/samples-java/blob/master/Advanced/auction-cordapp/client/src/main/java/net/corda/samples/client/AppConfig.java#L48
The Exception java.lang.IllegalArgumentException: object is not an instance of declaring class is something that happens if a method is called by reflection on an object which is of the wrong type.
In conjunction with jackson that may happen because a generic is lying to you. Here is an example:
class A (val x: String)
class B (val y: String)
class C (val z: List<A>)
ObjectMapper().writeValueAsString(C(listOf(B("x")) as List<A>))
This causes a compile warning, but it compiles and initially runs because of type erasure. However we forcefully injected a List<B> in a place where actually a List<A> is expected. While type erasure does remove quite a bit of information, it does not do so completely. Reflection can still be used to determine that C.z is actually of type List<A>. Jackson uses this information and tries to serialize an object of type A but instead finds an object of type B in the list and fails with the given message.
Check that your data structure actually contains the types that you expect!

EF Core 2.1 InvalidCastException on DbContext.Query<T>()

Given:
public class MyClass
{
public MyClass(ApplicationDbContext db)
{
var query = db.Query<IdentityUser>();
}
}
Using ASP.NET Core 2.1, I am getting this exception on the db.Query<IdentityUser>() call:
System.InvalidCastException: 'Unable to cast object of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet\`1[Microsoft.AspNetCore.Identity.IdentityUser]' to type 'Microsoft.EntityFrameworkCore.DbQuery\`1[Microsoft.AspNetCore.Identity.IdentityUser]'.'
I ran into this with my own entities and reproduced it with minimal code using the canned ApplicationDbContext/IdentityUser. Is this a bug in .NET Core 2.1 or am I doing something incorrectly?
This is the source code from github for DbContext.Query<T>():
public virtual DbQuery<TQuery> Query<TQuery>()
where TQuery : class
=> (DbQuery<TQuery>)((IDbQueryCache)this)
.GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery));
It appears to be throwing the exception casting ((IDbQueryCache)this).GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery)) to (DbQuery<TQuery>)
I've opened an issue on github since this seems to be a bug from what I can tell.
Comment on my github issued had the solution:
You cannot call Query<> method for EntityTypes. You must use Set<>
method.
It might be helpful for TQuery to be more constrained than just class if that is possible.

Jersey unable to catch any Jackson Exception

For my REST api I'm using jersey and ExceptionMapper to catch global exceptions.
It works well all the exception my app throws but I'm unable to catch exception thrown by jackson.
For example one of my endpoint accept an object that contains an enum. If the Json in the request has a value that is not in the enum jersey throw this exception back
Can not construct instance of my.package.MyEnum from String value 'HELLO': value not one of declared Enum instance names: [TEST, TEST2]
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream#5922e236; line: 3, column: 1] (through reference chain: java.util.HashSet[0]->....)
Even though I have created this mapper
#Provider
#Component
public class JacksonExceptionMapper implements ExceptionMapper<JsonMappingException> {
#Override
public Response toResponse(JsonMappingException e) {
....
}
}
The code never reach this mapper.
Is there anything we need to do in order to catch these exceptions?
EDIT
Note: I have jus tried being less general and instead of JsonMappingException I use InvalidFormatException in this case the mapper is called. But I still don't understand because InvalidFormatException extends JsonMappingException and should be called as well
Had the same problem.
The problem is that JsonMappingExceptionMapper kicks in before your mapper. The actual exception is of class com.fasterxml.jackson.databind.exc.InvalidFormatException and the mapper defines com.fasterxml.jackson.jaxrs.base.JsonMappingException, so it's more specific to the exception.
You see, Jersey's exception handler looks to find the most accurate handler (see org.glassfish.jersey.internal.ExceptionMapperFactory#find(java.lang.Class, T)).
To override this behavior, simply disable the mapper from being used:
Using XML:
<init-param>
<param-name>jersey.config.server.disableAutoDiscovery</param-name>
<param-value>true</param-value>
</init-param>
Using code: resourceConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); where resourceConfig is of type org.glassfish.jersey.server.ServerConfig.
You can also write your own specific mapper:
public class MyJsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException>
But I think it's an over kill.
Hi it seems to exits an alternative answer now that does not require to disable Jersey AUTO_DISCOVERY feature.
Just annotate your own exception mapper with a #Priority(1) annotation. The lower the number, the higher the priority. Since Jackson's own mappers do not have any priority annotation, yours will be executed:
#Priority(1)
public class MyJsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException>
Starting in version 2.29.1 [1], if you're registering the JacksonFeature, you can now do so without registering the exception mappers [2]:
register(JacksonFeature.withoutExceptionMappers());
[1] https://github.com/eclipse-ee4j/jersey/pull/4225
[2] https://eclipse-ee4j.github.io/jersey.github.io/apidocs/2.34/jersey/org/glassfish/jersey/jackson/JacksonFeature.html#withoutExceptionMappers--

Why won't Scala recognize that I'm extending ListModel<E>?

I am writing my own javax.swing.ListModel<E>:
class Category(...)
class CategoryListModel extends javax.swing.ListModel[Category] {
// not shown: ListModel[Category] interface methods implemented here
...
}
However, when I try to set the list model with:
val myList: JList = ...
myList.setModel(new CategoryListModel)
The compiler gives me this error:
type mismatch;
found : CategoryListModel
required: javax.swing.ListModel[?0] where type ?0
myList.setModel(new CategoryListModel)
I thought CategoryListModel did implement ListModel[Category]??? I am trying to learn Scala by practicing using it lately, but I don't know how to interperet this error.
Okay, so the error was originating in the fact that my JList did not have a type parameter specified (it was generated by a GUI builder). I changed the declaration to:
JList<Category> // this particular file is a Java file
Now everything works.

Linq to SQL - Serialization

How to mark System.Data.Linq.EntitySet and System.Data.Linq.EntityRef fields with with Serializable attribute the LINQ class.
In the Object Relational Designer, changed the Serialization Mode property to Unidirectional.
Still throwing below error:
Type 'System.Data.Linq.EntitySet`1 [[CIMS.Framework.DataAccess.Models.Assessments_ResponseWorkflow,
CIMS.Framework.DataAccess, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException:
Type 'System.Data.Linq.EntitySet`1
[[CIMS.Framework.DataAccess.Models.Assessments_ResponseWorkflow,
CIMS.Framework.DataAccess, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'
in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Any example please?
I'm not sure if this helps but you can serialize your LINQ-to-SQL generated classes by having manually created partial classes, that correspond to the LINQ-to-SQL partial classes, inherit a base entity which is flagged as serialized. For example:
[Serializable]
public abstract class BaseEntity
{
// Code...
}
public partial class Customer : BaseEntity
{
// Code...
}
This ensures that a LINQ-to-SQL class like Customer, and any other partial classes that inherit BaseEntity, are serialized.