Adding state to bean generated via CGLIB's BeanGenerator - cglib

I see the following example code on how a Java Bean can be created dynamically. What I am not able to figure out is how I can update the state of an instance once created.
So in the following example how can I set the value of foo to "footest" for instance bean?
BeanGenerator bg = new BeanGenerator();
bg.addProperty("foo", Double.TYPE);
bg.addProperty("bar", String.class);
Object bean = bg.create();
Thanks
Kumar

A few ways come to mind:
1/ Call "setFoo()" on "bean" using reflection. Not pretty.
2/ Use a helper library to do the same thing - e.g. Commons-Beanutils o.a.c.BeanUtils.PropertyUtils.setProperty(bean, "foo", "footest").
This way works nicely for me. You could use the Spring equivalent if you're already using Spring.
3/ Use CGLIB's BeanMap upon your new bean. e.g.
Map beanMap = BeanMap.create(bean);
beanMap.put("foo", "footest");

Related

Why #PetiteInject cannot inject service in DecoraManager?

I have a DecoraManager implementation : AppDecoraManager, and want to inject a service e.g.: FooService as:
#PetiteInject
FooService fooService;
When resolveDecorator() is called I want to use fooService to determine some parameters, but it has null value.
What could be the reason for this, and how could I resolve it?
DecoraManager is created by the servlet container, in DecoraServletFilter.
At the moment, there is no integration with existing Petite IOC, so you have to do the following:
First, you need to have a public static reference to PetiteContainer. Store it during the creation of container, for example.
Override createDecoraManager() in your implementation
Use PetiteContainer.wire(this) in your implementation of DecoraManager.
That is the only way to do so, so far.
The alternative would be this:
Register DecoraManager as #PetiteBean.
Again, get the static reference to PetiteContainer
In createDecoraManager use PetiteContainer.get() to get the instance.
In the first example, DecoraManager gets just wired; in the second example, it gets stored in Petite container, too.

Self referencing loop Detected for property in Asp.net MVC with Angular 2

I Have Create a DB in that I am Having Multiple tables having Relationship between them.
When a try to get data from my WEb app i get this error
"'Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PrescriptionMaster_2C4C63F6E22DFF8E29DCAC8D06EBAE038831B58747056064834E80E41B5C4E4A'. Path '[0].Patient.PrescriptionMasters"
I coudn't get why i am getting this error, and when i remove the relationships between tables i get proper data From it.
I have Tried other solutions like adding
"config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; "
in Webconfig.cs but nothing has worked for me.
Please help me, what should I do ?
The only proper way to prevent this from happening is by not sending Entity Framework objects (which may contain such loops) into the JSON Serializer (which is not too good at knowing when to stop serializing).
Instead, create ViewModels that mimic the parts of the EF Objects that your Front End actually needs, then fill those ViewModels using the EF Objects.
A quick-and-dirty way is to just use anonymous objects, for example:
return new
{
Product = new
{
Id = EF_Product.Id,
Name = EF_Product.Name
}
};
A good rule-of-thumb is to only assign simple properties (number, bool, string, datetime) from the EF Objects to the ViewModel items. As soon as you encounter an EF Object property that is yet another EF Object (or a collection of EF Objects), then you need to translate those as well to 'simple' objects that are not linked to EF.
On the other end of the spectrum there are libraries such as AutoMapper. If you decide that you need actual ViewModel classes, then AutoMapper will help mapping the EF Objects to those ViewModels in a very structured way.
Just add this to the Application_Start in Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
It will ignore the reference pointing back to the object.

StackOverflowError occurs when serialize nested objects to JSON string

Here is nested object in Groovy:
class A{
B b
}
class B{
A a
}
A a = new A()
B b = new B()
a.b = b
b.a = a
Then StackOverflowError occurs when new JsonBuilder(a).toString() is called.
Do we have any configuration for the JsonBuilder? Or it's impossible to do that. By the way, the nested objects is from Hibernate.
Thanks!
Based on the description of the question, it seems like you are dealing with data like this:
DB(Data) --> YourApp(POJO) --> External(JSON)
But, from the design perspective, I think this doesn't seem the right thing to do to expose your internal DB data model for external usage. It may be better for many reasons to use new models for serialization:
Security. As I mentioned above.
Extensibility. Even the model you are using are same for now, they may be changed and different in the future.
Simpleness.
If you're doing bidirectional relationship in Hibernate you can make objects hold reference to another (such as id) instead of the actual object which causes this problem.
With the given scenario and the error you are getting, it can be concluded that JsonBuilder does nto handle cyclic references (which is there in your object structure). I am not sure which library you are using but you can crosscheck that with the source code if available.
As an alternative, I would suggest to explore other libraries which handle the cyclic reference. Check Jackson which is known to handle cyclic references.

how to get getPooledConnection() on MysqlConnectionPoolDataSource

I have a class where i want the pool connection . I created MysqlConnectionPoolDataSource object and on that i'm calling the getPooledConnection() method like this
MysqlConnectionPoolDataSource datasource;
PooledConnection pconn=null;
pconn = dataSource.getPooledConnection();
when i am run the test class i am unable to get ant thing in
pconn = dataSource.getPooledConnection(); That is dataSource.getPooledConnection() returning nothing. How to fix this issue.
Thanks
Since you are using MysqlConnectionPoolDataSource in a test and not a Java EE container, you need to configure the object. At the very least I appears you will need to call setUrl(), setUser() and setPassword()

Linq to Sql - Unable to make a deep copy of an L2S entity

I am trying to make a deep copy of a L2S entity using the code below. I have the Serialization Mode of the .DBML set to Unidirectional. However, when I attempt to make a deep copy of an L2S entity, using the DeepCopy method shown below, I get an error saying the object isn't marked as serializable. Anyone know why?
public static T DeepCopy<T>(T obj)
{
object result = null;
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
result = (T)formatter.Deserialize(ms);
ms.Close();
}
return (T)result;
}
One of my L2S class definitions looks as follows:
[global::System.Data.Linq.Mapping.TableAttribute(Name="Polar.Recipe")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class RecipeRecord : INotifyPropertyChanging, INotifyPropertyChanged
DataContract attribute is required by DataContractSerializer but wont' work with other serializers like BinarySerializer, ViewStateSerializer and other serializers. In order to make them work You have to use Serializable attribute to apply to them. Now how to make that easy...
When I want to extend my Linq2Sql entities I usually abuse the fact that they are ALL partial classes. So I create file Linq2SqlExtensions.cs
public partial class LinqEntity
{
//extensions go here
}
and other extensions (like for example data context extensions). Now if You have many entities You can write a small program (even in powershell) to extract all class names out of Your Linq2Sql namespace/assembly (I pray You have them in another assembly) and create this file for You and automatically update it for You everytime YOu run it from VisualStudio Command line (or msBuild script).
something like
var entities = Assembly.Load("MyLinqAssembly").GetTypes().Where(p=> p.IsDefined(typeof(TableAttribute), true));
WriteEntityCsFile(entities);
Did you try adding Serializable attribute to your entity classes?
It's possible that DataContract attribute allows serialization only through WCF and other communication services, and not using BinaryFormatter.
Alternatively, try using DataContractSerializer instead BinaryFormatter.